使用以下数据框:
A1 A2 EFF FRQ
A G 0.0125 0.4578
T C 0.0143 0.1293
T C -0.017 0.8984
A G -0.018 0.8945
A G -0.009 0.8652
A G 0.0001 0.3931
我想提出两个概率" draw"来自基于FRQ
列的效果大小。我想创建一个名为sim_1
的新列,其中45.78%的时间,EFF
保留其标志,54.22%的时间,EFF
将其切换为&#{1}} #39;标志。我想为每一行总结其中两个随机事件。例如,假设生成两个随机数0-100。 78.33和32.16。我会采取任何< 45.78表示保持EFF
相同。由于我随机滚动了78和32,因此总和将为-0.0125(对于78.33卷)和对于(32.16)卷的0.0125,等于0.
在第二行,让我们说我滚动两个随机数88.22和67.10。因为这些数字都不低于12.93,所以对于88.22和67.10掷骰都会翻转EFF
符号,留下一个-0.0286(-0.0143 + -0.0143)的总和。
我想以这种方式做500个模拟列,以便最终输出如下:
A1 A2 EFF FRQ Sim_1 Sim_2 Sim_3...
A G 0.0125 0.4578 0 - -
T C 0.0143 0.1293 -0.0286 - -
T C -0.017 0.8984 - - -
A G -0.018 0.8945 - - -
A G -0.009 0.8652 - - -
A G 0.0001 0.3931 - - -
注意:如果您生成输出文件,它可能与我的不匹配,因为它基于随机性。
答案 0 :(得分:2)
使用您的数据:
tmp_df <- structure(list(A1 = structure(c(1L, 2L, 2L, 1L, 1L, 1L),
.Label = c("A", "T"), class = "factor"),
A2 = structure(c(2L, 1L, 1L, 2L, 2L, 2L),
.Label = c("C", "G"), class = "factor"),
EFF = c(0.0125, 0.0143, -0.017, -0.018, -0.009, 1e-04),
FRQ = c(0.4578, 0.1293, 0.8984, 0.8945, 0.8652, 0.3931)),
.Names = c("A1", "A2", "EFF", "FRQ"), class = "data.frame", row.names = c(NA, -6L))
执行以下操作
set.seed(0)
tmp_results <- lapply(1:500, function(i) rowSums(2 * (0.5 - (matrix(runif(nrow(tmp_df) * 2), ncol = 2) >= tmp_df$FRQ)) * tmp_df$EFF))
tmp_out <- as.data.frame(tmp_results)
names(tmp_out) <- paste("Sim", 1:500)
tmp_out <- cbind(tmp_df, tmp_out)
制造
> tmp_out[, 1:10]
A1 A2 EFF FRQ Sim 1 Sim 2 Sim 3 Sim 4 Sim 5 Sim 6
1 A G 0.0125 0.4578 -0.0250 0.0000 0.0250 -0.0250 0.0000 0.0250
2 T C 0.0143 0.1293 -0.0286 -0.0286 -0.0286 -0.0286 0.0000 -0.0286
3 T C -0.0170 0.8984 -0.0340 -0.0340 -0.0340 -0.0340 -0.0340 -0.0340
4 A G -0.0180 0.8945 -0.0360 0.0000 -0.0360 -0.0360 -0.0360 -0.0360
5 A G -0.0090 0.8652 0.0000 -0.0180 -0.0180 -0.0180 -0.0180 0.0000
6 A G 0.0001 0.3931 0.0002 -0.0002 -0.0002 0.0000 -0.0002 0.0000
lapply
步骤的说明:
1) matrix(runif(nrow(tmp_df) * 2)
Draw two columns filled with random numbers drawn uniformly in the interval [0, 1].
Alternatively, you can look into using `rbinom`.
2) 2 * (... >= tmp_df$FRQ) * tmp_df$EFF
Create (-1, 1) indicator to see whether `EFF` should be fliped, then multiply, exploiting conformability rules.
3) lapply(...)
Do the above 500 times.
其余的只是标记,并将模拟结果绑定到原始数据。