如何创建循环以在R中生成随机样本列表? [英] How to create a loop for generate a list of random samples in R?

查看:189
本文介绍了如何创建循环以在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
}

但是没有用!对于每个dep [i],我只有一个数字,而不是九个列表.

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?

非常感谢,希望您理解我想要的.

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

推荐答案

这是因为您已经将dep设置为向量(默认情况下为1D),但是您正在尝试在其中存储二维对象

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.

您可以在循环中以deprbind(行绑定)的方式关闭dep,而且请注意,除了在循环中使用count之外,您还可以使用i:

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)

但是,有一种更简单的方法.您不必逐行生成dep,您可以通过生成一个包含9*N个四舍五入的统一分布数的向量来预先生成它:

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))

现在,dep当前是长度为9 * N的向量.让我们将其放入Nx9矩阵:

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

dep <- matrix(dep,nrow=N)

完成!

因此,您可以在一行中完成以上所有代码:

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

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

如果需要,可以在dep上调用data.frame(将其放入2D矩阵形式后)以获取数据帧.

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.

这篇关于如何创建循环以在R中生成随机样本列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆