4

在 R 中,当应用 sample() 时,如果 replace 为真,当有超过250 个合理可能的值时,将使用 Walker 的别名方法。有没有办法让 sample() 总是使用别名方法?谢谢!

4

1 回答 1

1

一种选择是将您的向量xprob向量复制足够多的时间,以使结果向量的长度超过 250 个元素。当然,这是一个 hack,但很有趣!

sampleWalker <- function(x, size, prob) {
    nx <- length(x)
    nrep <- 251 %/% nx + 1
    sample(x = rep(x, nrep), size = size, replace = TRUE, prob = rep(prob, nrep))
}

sampleWalker(1:3, 10, prob = 1:3)
#  [1] 3 1 2 3 3 2 2 1 2 3
# Warning message:
# In sample.int(length(x), size, replace, prob) :
#   Walker's alias method used: results are different from R < 2.2.0
于 2012-12-14T03:34:31.197 回答