[R] Loop with variable index

Bill.Venables at csiro.au Bill.Venables at csiro.au
Thu Jan 31 00:17:11 CET 2008

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])

Easy peasy, ...

Bill Venables
CSIRO Laboratories
PO Box 120, Cleveland, 4163
Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):  +61 7 3826 7304
Mobile:                         +61 4 8819 4402
Home Phone:                     +61 7 3286 7700
mailto:Bill.Venables at csiro.au

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of cvandy
Sent: Thursday, 31 January 2008 5:59 AM
To: r-help at r-project.org
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
I want to find the mean and stnd. dev. of  the first 3 values, etc.
the last time through the loop I want to find the mean and stnd. dev. of
20 values,  so I end up with 19 means and stnd. deviations.
How would I construct such a loop?
View this message in context:
Sent from the R help mailing list archive at Nabble.com.

R-help at r-project.org mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list