循环数据帧的行以进行模拟

发布于 2024-11-27 21:42:38 字数 550 浏览 0 评论 0原文

这更像是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月流歌 2024-12-04 21:42:38

随机绘制函数都是矢量化的:

df$xSim01 = rhyper(20000, df$nR01, df$nR02, df$xRsum)

查看replicate以重复执行此操作并避免循环。您需要创建自己的函数来绘制观察结果并取平均值。像这样的东西:

draw.mean <- function(dat,n) {
   return( mean(rhyper(n,dat$nR01,dat$nR02,dat$xRsum)) )
}
replicate(1000,draw.mean(dat=df,n=20000))

The random draw functions are all vectorized:

df$xSim01 = rhyper(20000, df$nR01, df$nR02, df$xRsum)

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:

draw.mean <- function(dat,n) {
   return( mean(rhyper(n,dat$nR01,dat$nR02,dat$xRsum)) )
}
replicate(1000,draw.mean(dat=df,n=20000))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文