<Bill.Venables <at> csiro.au> writes: > > y <- sort(rnorm(20)) # say... > > m <- s <- numeric(19) > > for(i in 2:20) { > m[i-1] <- mean(y[1:i]) > s[i-1] <- sd(y[1:i]) > } > -----Original Message----- > On Behalf Of cvandy > Subject: [R] Loop with variable index > I have a list of 20 values. The first time through a loop I want to > find the > mean and stnd.dev. of the first two values; the second time through the > loop I want to find the mean and stnd. dev. of the first 3 values, etc. > until the last time through the loop I want to find the mean and stnd. dev. > of > all 20 values, so I end up with 19 means and stnd. deviations. > How would I construct such a loop? > Thanks.
Just for an alternative to some of the sapply solutions, the means can also be obtained with (cumsum(y)/(1:length(y)))[-1] ken ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.