Random draws with a vector of probabilities

Viewed 529

I have a vector of probabilities. With the probabilities, I want to draw a sample between (0,1) for each probability.

For example, prob_of_one indicates that 1 is drawn ((1-prob_of_one) is the probability that 0 is drawn).

data.frame(prob_of_one = c(runif(100)),desire_column = NA)

How can I have 0 or 1 value by sampling without using for-loop?

2 Answers

Remember that rbinom takes vector arguments, including for its probabilities. Thus, you only need to say:

rbinom(100,size=1,prob=prob_of_one)

I know you didn't ask, but remember that R's recycling rules can be used, so if you wanted 2 sets of 100 in the same vector, you could say

rbinom(200,size=1,prob=prob_of_ones)

It would also work if your probability vector had a length that evenly divides 100. The below gives a draw when probability of 1 is (1/3,1/5) repeated 50 times.

rbinom(100,size=1,prob=c(1/3,1/5))

Benchmarking

## transform 
c1<-function(n=100) {
  dd <- data.frame(prob_of_one = runif(n))
  transform(dd, draw = ifelse(runif(length(prob_of_one))<prob_of_one, 1, 0))
}

##rbinom
c2<-function(n=100){
  set.seed(101)
  prob_of_one=runif(n)
rbinom(n,size=1,prob=prob_of_one)
}

> benchmark(transform_method=c1(100),my_method=c(100),replications=1000) %>% kable

|   |test             | replications| elapsed|relative | user.self| sys.self| user.child| sys.child|
|:--|:----------------|------------:|-------:|:--------|---------:|--------:|----------:|---------:|
|2  |my_method        |         1000|    0.00|NA       |      0.00|        0|         NA|        NA|
|1  |transform_method |         1000|    0.47|NA       |      0.47|        0|         NA|        NA|

You could do this by just drawing a random number between 0 and 1. If the random number is less than the "probability of 1" then you draw 1, otherwise draw 0. For example

set.seed(101)
dd <- data.frame(prob_of_one = runif(100))
transform(dd, draw = ifelse(runif(length(prob_of_one))<prob_of_one, 1, 0))

This works because if you have a probability of 1 equal to .9 for example, and you randomly draw from a uniform(0,1) distribution, 90% of the time it will be less than .9.

Related