[R] Loop with variable index
Ken Knoblauch
knoblauch at lyon.inserm.fr
Thu Jan 31 00:41:12 CET 2008
<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
More information about the R-help
mailing list