[英]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
列從效果大小中得出兩個概率“吸引”。 我想創建一個名為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.
其余的只需標記,然后將模擬結果綁定到原始數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.