本文介绍了给定R中的特定概率值,生成随机数(0和1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中找不到此问题的答案.我想生成一个0到1的'RandomSample'的随机样本.对于每个样本,我希望有一个特定数量的值"numval",它是从向量"Prob"的长度得出的. 概率"为我提供了每个单独点将为0或1的概率值.因此,在这种情况下,第一个数字的概率值将为0.9等于1,而0.1等于0.依此类推.然后,我想将随机样本生成重复1000次.我有一个脚本(如下),生成随机的0和1,但是缺少给出概率值的组件.帮助将不胜感激-我对R还是陌生的.

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 number of values 'numval' which is derived from the length of the vector 'Prob'. 'Prob' is giving me probability value that each individual point will be 0 or 1. So in this instance first number will have prob value of 0.9 being 1, and 0.1 being 0. And so on. Then, I would like to repeat random sample generation 1000 times. I have a script (below) generating random 0 and 1's but I am missing component on giving the probability values. Help will be much appreciated - I am fairly new to 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))

推荐答案

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

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

尝试一下:

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()使用您的概率重复绘制样本:

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

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

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

这篇关于给定R中的特定概率值,生成随机数(0和1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:24