Generating random numbers (0 and 1) given specific probability values in R

后端 未结 2 604
梦谈多话
梦谈多话 2021-01-14 12:34

I could not find answer for this question in R. I would like to generate a random sample of 0 to 1\'s \'RandomSample\'. For each sample I would like to have a specific numbe

相关标签:
2条回答
  • 2021-01-14 12:48

    You could use rbinom():

    Prob <- c(0.9, 0.3, 0.6, 0.8, 0.23, 0.45, 0.1, 0.3, 0.5, 0.03) #specify vector of probabilities
    niter<- 1000 #number of iterations
    randomSample<-rbinom(niter,1,prob=rep(Prob,niter)) #randomly sample from binomial with vector of probabilities. 
    
    0 讨论(0)
  • 2021-01-14 13:07

    You can use rbinom() to generate random samples from a binomial distribution.

    Try this:

    prob <- c(0.9, 0.3, 0.6, 0.8, 0.23, 0.45, 0.1, 0.3, 0.5, 0.03)
    rbinom(length(prob), size = 1, prob=prob)
    
     [1] 1 1 1 0 0 0 0 1 0 0
    

    To demonstrate that the probabilities are in fact what you are after, try using replicate() to repeatedly draw samples using your probabilities:

    x <- t(replicate(100, rbinom(length(prob), size = 1, prob=prob)))
    head(x)
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    [1,]    1    0    1    1    1    1    0    0    1     0
    [2,]    1    1    1    1    0    1    0    1    0     0
    [3,]    1    0    1    1    0    0    0    1    0     0
    [4,]    1    0    1    0    0    1    0    0    1     0
    [5,]    1    1    1    1    0    0    0    0    0     0
    [6,]    1    0    0    0    0    0    0    0    0     0
    

    Now you can use colMeans() to compare the actual achieved probability against your specification:

    colMeans(x)
     [1] 0.93 0.28 0.61 0.67 0.25 0.43 0.11 0.29 0.40 0.01
    
    0 讨论(0)
提交回复
热议问题