How can I speed up probability-weighted Sampling in R.
# Let's assume we are considering following example:
w <- sample(1:4000,size=2e6, replace=T)
# "w" will be integer, so we are going to convert it to numeric.
w <- as.numeric(w)
# Actually the sampling process have to be repeated many times.
M <- matrix(NA, 10, 2000)
system.time(
for (r in 1:10){
ix <- sample(1:2e6,size=2000,prob=w/sum(w))
M[r,] <- ix
})
# It's worth it to mention that without "prob=w/sum(w)" sampling is considerably faster.
# The main goal is to speed up sampling with probability weights!
system.time(ix <- sample(1:2e6,size=2000,prob=w/sum(w)))
A weighted sampling takes 9.84 sec., normal sampling 0.01 sec. If you have any idea how it is possible to speed up weighted sampling, please feel open to answer.