Probability, sample function - intervals

Viewed 39

I have a problem with the sample function. I have an error that incorrect number of probabilities. Can I use probability in another way? I don't know that this function works on intervals.

OL_x = c(15.0:47.0,0.0:15.0,47:80,80:105)
x = sample(OL_x,1000,replace = TRUE,prob = c(0.60,0.22,0.13,0.05) )+ runif(1000,0,1)
2 Answers

You need to have a probability associated with each value, i don't know a way to assign a probability to an interval, so doing it "by hand" could be like:

probs = c(rep(0.60, 48-15), rep(0.22,16-0), rep(0.13, 81-47), rep(0.05, 106-80))

x = sample(OL_x, 1000, replace = TRUE, prob = probs) + runif(1000,0,1)

This is not much efficient because you need to calculate the size of each interval by hand, there are probably better ways of doing this.

The prob argument can be length 1 or one value for each element of x. OL_x is a vector with 109 elements, since the : integer sequence operator expands out your values. Not quite sure what you are trying to create, but if you are after 1000 values drawn from the values presented with the probabilities described, try:

# keep groups separate as a list
OL_x = list(15.0:47.0,0.0:15.0,47:80,80:105)
# number of values in each group
vapply(X = OL_x, FUN = length, FUN.VALUE = 0L)
# [1] 33 16 34 26
# create 109 probabilities
rep(c(0.60,0.22,0.13,0.05), times = vapply(X = OL_x, FUN = length, FUN.VALUE = 0L))
#  [1] 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60
# [14] 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.60
# [27] 0.60 0.60 0.60 0.60 0.60 0.60 0.60 0.22 0.22 0.22 0.22 0.22 0.22
# ...
# create 1000 samples 
x = sample(
    x = unlist(OL_x), 
    size = 1000, 
    replace = TRUE, 
    prob = rep(c(0.60,0.22,0.13,0.05), 
        times = vapply(X = OL_x, FUN = length, FUN.VALUE = 0L))
) + runif(1000,0,1)
head(x)
# [1] 18.826530 36.948981 15.366685  5.142625 47.659682 14.946690
Related