簡體   English   中英

R data.table:生成隨機數

[英]R data.table: Generate random numbers

我有一個大的data.table ,我試圖生成二項式隨機數(使用rbinom )使用其中一列的值作為分布的參數。 假設index是唯一的行標識符,並且該參數位於responseProb列中。 然后

dt[, response := rbinom(1, 1, responseProb), by = index]

rbinom的簽名是rbinom(n, size, prob) ,但由於它沒有在prob參數上進行矢量化,因此它只能將標量作為輸入,所以我不能,但能夠寫:

dt[, response := rbinom(1, 1, responseProb)]

舉一個我的意思的簡單例子, rbinom(1, 1, seq(0.1, 0.9, .1)) ,得到

> rbinom(1, 1, seq(0.1, 0.9, .1))
[1] 1

我認為解決這個問題的方法是使用

dt[, response := rbinom(probResponse, 1, responseProb)]

但是要仔細檢查這是否會導致與第一行代碼相同的答案。

所以rbinom是矢量化的,你可以使用.N作為第一個參數。

dt[, response := rbinom(.N, 1, responseProb)]

要檢查這是否與索引解決方案提供相同的結果,只需設置種子並重復。

# create reproducible example
N <- 100
dt <- data.table(responseProb = runif(N), 
                 index = 1:N)
# set seed
set.seed(1)
# your original version
dt[, response := rbinom(1, 1, responseProb), by = index]
# set seed again
set.seed(1)
# version with .N
dt[, response2 := rbinom(.N, 1, responseProb)]
# check for equality
dt[, all(response == response2)]
## [1] TRUE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM