"incorrect number of probabilities" error using sample()

blackhawk picture blackhawk · Aug 2, 2016 · Viewed 7.2k times · Source

I was trying sample(), however whenever I used custom probability in it ,it constantly displays "incorrect number of probabilities"

I've tried pretty much everything but still stuck. Kindly guide me as to what I am doing wrong..

Code:

sample(10:50,4,replace = T,prob = c(.1,.2,.3,.4))   

Error in sample.int(length(x), size, replace, prob) :
incorrect number of probabilities

Answer

Robert Long picture Robert Long · Aug 2, 2016

When you are sampling data, by default, each item in the vector you are sampling from has an equal probability of being sampled. In your case, you are sampling from the vector 10:50, that is, the vector containing all the 41 values from 10 to 50. However the custom probability vector length is 4, whereas it should be 41. Alternatively, the vector you want to sample from should be of length 4:

sample(1:4,4,replace = T,prob = c(.1,.2,.3,.4))