循环数据帧的行以进行模拟
这更像是 R 编程问题,而不是任何概念问题。我尝试过,但缺乏 R 方面的专业知识让我感到沮丧:
我有一个数据框 df,其中包含 ID、xR01、xR02、nR01、nR02、xRsum 列,我想使用超几何函数来生成模拟数据。对一个值执行此操作很简单:
df$xSim01 = rhyper(1, df$nR01, df$nR02, df$xRsum)
但我的问题是,如果我以上面的形式应用它,它似乎为所有 20,000 行提供了一个值。这让我觉得如果我循环每一行它可能会正常工作。那么使用 apply、with 或任何其他函数最有效的是什么?
我的第二个问题是:
我想首先模拟这两个 20,000 行以获得第一个模拟数据集,然后想要获得该模拟列的平均值,并以某种方式存储该平均值并重复模拟 N 次。如此嵌套循环,希望找到有效的方法来节省计算时间。在 R 中正确的代码将受到赞赏。谢谢
dat.sim$xR01 <- rhyper(1, dat.obs$nR01, dat.obs$nR02, dat.obs$xRsum)
This is more of a programing in R question than any concept question. I tried but my lack of expertise in R is frustrating me:
I have a dataframe df with columns ID, xR01, xR02, nR01, nR02, xRsum, and I want to use hypergeometric function to generate simulated data. Doing this for one value is simple:
df$xSim01 = rhyper(1, df$nR01, df$nR02, df$xRsum)
But my problem is if I apply this in above form it seems like it gives me one value for all 20,000 rows. This made me think it might work properly if I loop over each row. So what will be most efficient using apply, with or any other function?
My second question is:
I will like first to simulate these two 20,000 rows to get first simulated data set, then would want to get mean of that simulated column, and store that mean in some way and repeat simulation for N number of times. So kind of nested loop, and want to find efficient way to save computation time. In proper code in R will be appreciated. Thanks
dat.sim$xR01 <- rhyper(1, dat.obs$nR01, dat.obs$nR02, dat.obs$xRsum)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
随机绘制函数都是矢量化的:
查看
replicate
以重复执行此操作并避免循环。您需要创建自己的函数来绘制观察结果并取平均值。像这样的东西:The random draw functions are all vectorized:
Look at
replicate
for doing this repeatedly and avoiding a loop. You'll want to create your own function that draws the observations and takes the mean. Something like: