[R] looping

Michael Toews mwtoews at sfu.ca
Tue Feb 27 06:51:13 CET 2007


Another way is to use an indexed list, which is far more tidier than 
your method. If you mean "about 100" as in an irregular number, then a 
list is your friend (i.e., a ragged array, that can have sometimes 97 
samples, sometime 105 samples, etc.). Similar to your example:

dat <- runif(100000,0,100) # fake dataset
smp <- list() # need an empty list first
for(i in 1:1000)
    smp[[i]] <- sample(dat,100)

However, if you are new to R/S, the best advice is to learn to _not_ use 
the for loop (because it is slow, and there are "vectorized" ways). For 
example, if we want to find the mean of each sample, then return a tidy 
result:

sapply(samp,mean)

or a crazy new analysis you might be working on:

crazy <- function(x,y) (sum(x>y)^2)/sum(x)
sapply(smp,crazy,10)

etc.
+mt



More information about the R-help mailing list