Re: [R] Loop with variable index

From: Ken Knoblauch <knoblauch_at_lyon.inserm.fr>
Date: Wed, 30 Jan 2008 23:41:12 +0000 (UTC)

 <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_at_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. Received on Wed 30 Jan 2008 - 23:44:16 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 31 Jan 2008 - 01:30:09 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive