Search code examples
rprobability

R- How to randomly select from two different probabilities?


I am looking to assign two different weighted probabilities (0.3 and 0.7). Each time (loop?) i want R to randomly select one of the two weighted probabilities. Then i need those data output in a dataframe.

I've tried a number of ways with no success. I am still a beginner.

Here is my noob code which doesn't work. I tried to sample the columns randomly. Thanks.

roll_it<-c(1:100)
n70<- 1; p70<-7/10
n30<- 1; p30<-3/10

for( i in roll_it){ 
        result <- c(rbinom(n30, 1, p30), rbinom(n70, 1, p70))
        
        print(result)}

sample(result(1:2,), size=2, replace = F)

Solution

  • If I understand your your goal correctly you don't need to use a loop at all. Just create two samples and then sample from that mixture distribution.

    set.seed(1)
    
    cc <- cbind(rbinom(100, 1, 0.3), rbinom(100, 1, 0.7))
    colMeans(cc)
    # [1] 0.32 0.70
    sample(cc, 2)
    # [1] 0 0