使用R以给定的概率生成两个值之间的随机整数 [英] generate random integers between two values with a given probability using R

查看:85
本文介绍了使用R以给定的概率生成两个值之间的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下四个数字集:

A=[1,207];
B=[208,386];
C=[387,486];
D=[487,586].

我需要生成1到586之间的20000个随机数,其中生成的数字属于A且属于B,C,D的概率为1/6.

I need to generate 20000 random numbers between 1 and 586 in which the probability that the generated number belongs to A is 1/2 and to B,C,D is 1/6.

我可以通过哪种方式使用R?

in which way I can do this using R?

推荐答案

您可以直接使用sample,更具体地说是probs自变量.只需将概率除以所有586个数字即可.类别A分别获得0.5/207的重量,等等.

You can directly use sample, more specifcally the probs argument. Just divide the probability over all the 586 numbers. Category A get's 0.5/207 weight each, etc.

A <- 1:207
B <- 208:386
C <- 387:486
D <- 487:586
L <- sapply(list(A, B, C, D), length)

x <- sample(c(A, B, C, D),
            size = 20000,
            prob = rep(c(1/2, 1/6, 1/6, 1/6) / L, L),
            replace = TRUE)

这篇关于使用R以给定的概率生成两个值之间的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆