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
depa vector (these are 1D by default), but you’re trying to store a 2-dimensional object in it.You can
depoff asNULLandrbind(row-bind) to it in the loop.Also, note that instead of usingcountin your loop you can just usei:However, there’s a simpler way to do this. You don’t have to generate
deprow-by-row, you can generate it up front, by making a vector containing9*Nof your rounded uniform distribution numbers:Now,
depis currently a vector of length 9*N. Let’s make it into a Nx9 matrix:Done!
So you can do all your code above in one line:
If you want you can call
data.frameondep(after it’s been put into its 2D matrix form) to get a data frame.