I'd like to create a large number of samples in R and store them in a variable. I did some research and probably the best way is to use replicate()
record <- replicate(5000, sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1)))
My question is how would I do it using for loop? I can create 5000 samples using for loop but how do I store them?
x <- 'something here' #I want to store them in x
for (i in 1:5000)
{record <- sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1))
'x += record'}
Edit: The line X+= record is confusing. Here is my best shot at explaining that, in python I'd create a list and inside that list there'd be 5000 other lists each containing a different sample
I see no point in using a for
loop; nor is there a need for replicate
.
You can draw 5000 * 60
independent samples directly using
smpl <- sample(c(0, 1), size = 60 * 5000, replace = TRUE, prob = c(0.9, 0.1))
If you want to store smpl
in a matrix, you can recast the vector as a matrix
, eg
mat <- matrix(smpl, ncol = 5000)
This will give you a 60 x 5000
matrix, where every column contains 5000
random samples drawn from a distribution with p(0) = 0.9
and p(1) = 0.1
.
This will be faster than using a for
loop or replicate
.
What about
x <- list() # or x <- c() or x <- data.frame()
for (i in 1:5000){
record <- sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1))
x[[i]] <- record # or x <- c(x, record) or x <- rbind(x, record)
}
But yeah, not using a loop is probably better here, as indicated above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.