【问题标题】:Generating random numbers (0 and 1) given specific probability values in R给定 R 中的特定概率值,生成随机数(0 和 1)
【发布时间】:2015-04-16 23:37:51
【问题描述】:

我在 R 中找不到这个问题的答案。 我想生成一个 0 到 1 的“RandomSample”随机样本。对于每个样本,我希望有一个特定数量的值“numval”,它来自向量“Prob”的长度。 'Prob' 给我的概率值是每个点都是 0 或 1。所以在这种情况下,第一个数字的概率值 0.9 为 1,0.1 为 0。依此类推。然后,我想重复随机样本生成 1000 次。我有一个生成随机 0 和 1 的脚本(如下),但我缺少给出概率值的组件。非常感谢您的帮助 - 我对 R 很陌生。

Prob <- c(0.9, 0.3, 0.6, 0.8, 0.23, 0.45, 0.1, 0.3, 0.5, 0.03)
RandomSample <- list()
zeroones <- c(0,1)
rep = 1000
numval <- length(Prob)

for (i in 1:rep) RandomSample[[i]] <- c(sample(zeroones,numval,replace = TRUE))
t(sapply(RandomSample, unlist, simplify = TRUE))

【问题讨论】:

  • 试试这个for (i in 1:rep) RandomSample[[i]] &lt;- c(sample(zeroones,numval,prob = Prob[i],replace = TRUE))
  • 在运行 stackoverflow 之前,您可以在提示符中尝试一个简单的“?sample”。它为您提供了明确定义如何设置随机变量概率的文档。

标签: r random probability sample random-sample


【解决方案1】:

你可以使用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. 

【讨论】:

    【解决方案2】:

    您可以使用rbinom() 从二项分布中生成随机样本。

    试试这个:

    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
    

    要证明概率实际上就是您所追求的,请尝试使用replicate() 使用您的概率重复抽取样本:

    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
    

    现在您可以使用colMeans() 将实际实现的概率与您的规范进行比较:

    colMeans(x)
     [1] 0.93 0.28 0.61 0.67 0.25 0.43 0.11 0.29 0.40 0.01
    

    【讨论】:

    • 如果你想要 1000 次迭代,你需要以某种方式重复 rbinom()。您可以按照@Andrie 的代码并将rep(rbinom(...),1000) 添加到此。我还展示了一种稍微不同的方法来返回 1000 个实例。
    猜你喜欢
    • 2013-04-21
    • 2016-01-06
    • 1970-01-01
    • 2014-03-01
    • 2012-12-04
    • 2015-05-18
    • 2021-08-27
    • 2013-06-04
    相关资源
    最近更新 更多