Alias โ€‹โ€‹Method in Sample ()

In R, when using sample (), if replace is true, the Walker alias method is used if there are more than 250 reasonably likely values. Is there a way to force sample () to always use the alias method? Thanks!

+4
source share
1 answer

One option is to repeat your x and prob enough for the resulting vectors to be longer than 250 elements. It's a hack, of course, but fun!

 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 alias method used: results are different from R < 2.2.0 
+1
source

All Articles