简体   繁体   中英

How to create a loop for generate a list of random samples in R?

I'm trying to create a loop that creates a series of objects that contains a random sample, like this:

sample <- ceiling(runif(9, min=0, max=20))

(This is an example for a rounded uniform, but it can be replaced by a normal, poisson or whatever you want).

So, I built a loop for generate automatically various of those generators, with the objective of include them in a data frame. Then, the loop I designed was this:

N=50
dep=as.vector(N)
count=1
for (i in 1:N){
    dep[count] <- ceiling(runif(9, min=0, max=20))  
    count=count+1
}

But it didn't work! For each dep[i] I have only a number, not a list of nine.

How I should do it? And if I want to include every dep[i] in a data frame?

Thanks so much, I hope you understand what i want.

It's because you've made dep a vector (these are 1D by default), but you're trying to store a 2-dimensional object in it.

You can dep off as NULL and rbind (row-bind) to it in the loop.Also, note that instead of using count in your loop you can just use i :

dep <- NULL
for (i in 1:N){
    dep <- rbind(dep,  ceiling(runif(9, min=0, max=20)))
}
# if you look at dep now it's a 2D matrix.
# We'll convert to data frame
dep <- as.data.frame(dep)

However , there's a simpler way to do this. You don't have to generate dep row-by-row, you can generate it up front, by making a vector containing 9*N of your rounded uniform distribution numbers:

dep <- ceiling(runif(9*N,min=0,max=20))

Now, dep is currently a vector of length 9*N. Let's make it into a Nx9 matrix:

dep <- matrix(dep,nrow=N)

Done!

So you can do all your code above in one line:

dep <- matrix( ceiling(runif(9*N,min=0,max=20)), nrow=N )

If you want you can call data.frame on dep (after it's been put into its 2D matrix form) to get a data frame.

As @mathematical.coffee explained. But also, it seems in your case for runif , you can use sample instead. And actually sample.int is more reliable. ...And about 3x faster than using runif here):

N <- 1000000
system.time( dep <- matrix(sample.int(20, 9*N, replace=TRUE), N) )  # 0.16 secs
range(dep) # 1 20

system.time( dep <- matrix(ceiling(runif(9*N, min=0, max=20)), N) ) # 0.45 secs
range(dep) # 1 20

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM