2015-04-14 138 views
1

我有一個大data.table,我使用的列作爲參數傳遞給分佈的一個值試圖生成二項式隨機數(使用rbinom)。假設index是唯一的行標識符,並且該參數位於responseProb列中。然後[R data.table:產生隨機數

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 

我認爲,要解決這個爲t o使用

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

但想仔細檢查一下,這將導致與第一行代碼相同的答案。

+1

rbinom是向量化的prob參數。但它只會使用/產生儘可能多的觀察結果。所以你要確保你的n至少和probs一樣長。 – Dason

+0

如果你給了一個[可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),這將有助於... –

回答

2

所以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