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

时间秒杀一切 提交于 2019-12-07 12:56:38

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/9832268/how-to-create-a-loop-for-generate-a-list-of-random-samples-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!