如何在 R 中制作概率模拟器?

How to make a probability simulator in R?

具有以下数据框:

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   

我想从基于 FRQ 列的效应大小中得出两个概率 "draws"。我想创建一个名为 sim_1 的新列,其中 45.78% 的时间 EFF 保持它的符号,而 54.22% 的时间 EFF 切换它的符号。然后我想对每一行的这些随机事件中的两个求和。例如,假设生成了两个随机数 0-100。 78.33 和 32.16。我将任何小于 45.78 的值都表示保持 EFF 相同。由于我随机掷出 78 和 32,总和将为 -0.0125(78.33 掷骰)和 0.0125(32.16)掷骰,等于 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  -        -       -

注意:如果您生成输出文件,它可能与我的不匹配,因为它是基于随机性的。

使用您的数据:

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.

剩下的只是简单的标注,然后将模拟结果绑定到你的原始数据上。