[R] for loop help, repeat a function multiple times
arun
smartpink111 at yahoo.com
Mon Oct 28 19:16:10 CET 2013
Hi,
You may try:
x <- 1:5
set.seed(49)
mat1 <- do.call(rbind,lapply(1:1000,function(y) sample(x,3)))
#or
mat2 <- matrix(0,ncol=3,nrow=1000)
set.seed(49)
for(i in seq_len(nrow(mat2))) mat2[i,] <- sample(x,3)
all.equal(mat1,mat2)
#[1] TRUE
#or
set.seed(49)
mat3 <- t(replicate(1000,sample(x,3)))
all.equal(mat2,mat3)
#[1] TRUE
A.K.
Hi, I have written a program that runs a series of calculations using
random numbers, so that each time that I run the program I get a vector
with different results. I need to repeat this program multiple times and combine all of the vectors into a single data frame or matrix. I am
fairly certain that a "for loop" is what I need, but after digging
around online and in multiple books, I am very confused about how to set up the loop. Just as an example, suppose that I want to randomly select 3 numbers from 1 to 5. I could do it using the following two lines:
x <- 1:5
y <- sample(x,3)
now suppose that I want to do this 1000 times, how do I set up a
loop that will give me 1000 iterations of y (i.e. it will select 1000
sets of 3 values ranging from 1:5)? In other words, how do I loop y a
specified number of times?
Thanks for the help
More information about the R-help
mailing list