[英]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.
对于每个dep [i]我只有一个数字,而不是九个列表。
How I should do it? 我应该怎么做? And if I want to include every dep[i] in a data frame?
如果我想在数据框中包含每个dep [i]?
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. 这是因为你做了
dep
向量(这些是默认1D),但你要保存的二维物体在里面。
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
和rbind
(行绑定)将其在loop.Also,注意,而不是使用count
在循环你可以使用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
,您可以通过制作包含9*N
圆形均匀分布数的向量来dep
生成它:
dep <- ceiling(runif(9*N,min=0,max=20))
Now, dep
is currently a vector of length 9*N. 现在,
dep
是一个长度为9 * N的向量。 Let's make it into a Nx9 matrix: 让我们把它变成一个Nx9矩阵:
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. 如果你想要,你可以在
dep
上调用data.frame
(在它被放入2D矩阵形式之后)来获取数据帧。
As @mathematical.coffee explained. 正如@ mathematical.coffee解释的那样。 But also, it seems in your case for
runif
, you can use sample
instead. 但是,在你的情况下似乎对于
runif
,你可以使用sample
代替。 And actually sample.int
is more reliable. 实际上
sample.int
更可靠。 ...And about 3x faster than using runif here): ......比使用runif快3倍左右):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.