开发者

Looping over rows of a data frame to simulate

开发者 https://www.devze.com 2023-03-25 12:11 出处:网络
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:

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 开发者_JAVA百科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)


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

精彩评论

暂无评论...
验证码 换一张
取 消