[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
AUSTRALIA
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
http://www.cmis.csiro.au/bill.venables/ 

-----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
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. 
-- 
View this message in context:
http://www.nabble.com/Loop-with-variable-index-tp15190661p15190661.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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.



More information about the R-help mailing list