Luis Correia
Luis Correia

Reputation: 19

How to generate a random sample according with a vector of different probabilities in a single command in R?

I need to simulate a vote cast ([0]=Reject, [1]=Approve) of a fictitious population according with their "probability to approve" (i.e., their probability to cast a vote [1]). Each individual (id) has a home state (uf) which has supposedly a different probability to approve (prob_approve) and which is considered known in this toy example.

Here is an example of the data:

pop_tab <- read.table(header=TRUE,sep=',',text = "id,uf,prob_approve
1,SC,0.528788386
2,AM,0.391834279
3,RJ,0.805862415
4,SP,0.762671162
5,CE,0.168054353
6,MG,0.78433876
7,PR,0.529794529
8,PA,0.334581091
9,SP,0.762671162
10,PA,0.334581091")

I tried:

x <- list(prob = pop_tab$prob_approve)

vote <- lapply(x, runif)

... but I don't think the 'runif()' function was processed with the probabilities on column "prop_approve".

How could I simulate the vote cast of the population, according with their home-state probabilities, in a single command, without having to process line by line in a for loop?

Thank you in advance.

Upvotes: 0

Views: 169

Answers (1)

Vincent
Vincent

Reputation: 17823

Use rbinom():

pop_tab <- read.table(header=TRUE,sep=',',text = "id,uf,prob_approve
1,SC,0.528788386
2,AM,0.391834279
3,RJ,0.805862415
4,SP,0.762671162
5,CE,0.168054353
6,MG,0.78433876
7,PR,0.529794529
8,PA,0.334581091
9,SP,0.762671162
10,PA,0.334581091")

rbinom(n = nrow(pop_tab),
       size = 1,
       prob = pop_tab$prob_approve)
##  [1] 0 0 1 0 0 1 1 1 1 1

Upvotes: 1

Related Questions