简体   繁体   English

R-如何从两个不同的概率中随机选择 select?

[英]R- How to randomly select from two different probabilities?

I am looking to assign two different weighted probabilities (0.3 and 0.7).我希望分配两个不同的加权概率(0.3 和 0.7)。 Each time (loop?) i want R to randomly select one of the two weighted probabilities.每次(循环?)我希望 R 随机 select 两个加权概率之一。 Then i need those data output in a dataframe.然后我需要dataframe中的那些数据output。

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)

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

Use sample() .使用sample()

roll_it < -c(1:100)
n70<- 1
n30<- 1

probabilities <- c(0.3, 0.7)
for(i in roll_it){ 
    result <- rbinom(x = n30, size = 1, prob = sample(probabilities, 1))
    print(result)
}

May I add, I'm not sure why are you using n30 and n70.我可以补充一下,我不确定你为什么使用 n30 和 n70。 Could you just use one of them?你可以只用其中一个吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM