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

I am trying to create a loop that creates a series of objects containing a random sample, for example:

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

      

(This is an example of a rounded uniform, but can be replaced with a regular, Poisson, or whatever you want.)

So, I built a loop to automatically generate different of these generators for inclusion in the data frame. Then I constructed this loop:

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 only have a number, not a list of nine.

How am I supposed to do this? And if I want to include every dep [i] in a data frame?

Thanks a lot, I hope you understand what I want.

+3


source to share


2 answers


This is because you made a dep

vector (which is 1D by default), but you are trying to store a 2D object in it.

You can dep

disable like NULL

and rbind

(row-bind) to it in a loop. Also note that instead of using count

in your loop, you can simply 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 a 2D matrix.
# We'll convert to data frame
dep <- as.data.frame(dep)

      

However , there is an easier way to do this. You don't need to generate dep

row-by-row rows , you can generate it in front by creating a vector containing 9*N

your rounded uniform spread numbers:

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

      

Now it dep

is currently a vector of length 9 * N. Let's turn into an 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 has been placed in its 2D matrix form) to get the dataframe.

+6


source


As @ Mathematical.coffee explained. But also it seems in your case for runif

, you can use sample

instead. And actually sample.int

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

      

+6


source







All Articles