[R] Loop with variable index

Rolf Turner r.turner at auckland.ac.nz
Wed Jan 30 21:14:24 CET 2008


On 31/01/2008, at 8:58 AM, cvandy wrote:

>
> I have a list of 20 values.

	***NO***!  You have (or should have) a *vector* of 20 values.
	Vectors and lists are different concepts.  Learn and understand
	the difference, else the world will come to an end.

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

	Why (on earth) would you want to do this?

> How would I construct such a loop?

	Let the vector be ``x''.
	
	mns <- list()
	sds <- list()
	for(i in 2:20) {
		mns[[i-1]] <- mean(x[1:i])
		sds[[i-1]] <- sd(x[1:i])
	}
	mns <- unlist(mns)
	sds <- unlist(sds)

	will do what you want.

cheers,

	Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list