简体   繁体   English

R 根据条件生成随机数

[英]R Generate random numbers based on condition

I'd like to generate a sequence of 100 numbers based on the following conditions -我想根据以下条件生成 100 个数字的序列 -

  • The numbers range from 1 to 5, and are whole numbers.数字范围从 1 到 5,并且是整数。
  • The number of 1s and 2s generated as a percentage of the total equals 90%生成的 1 和 2 的数量占总数的 90%

My Attempt我的尝试

I attempted to create the sequence using runif .我尝试使用runif创建序列。 However I am unsure about how to include the second condition.但是我不确定如何包含第二个条件。

v=c(1,2,3,4,5)
rep(sample(v),100)

Your help on the second condition would be greatly appreciated您对第二个条件的帮助将不胜感激

As indicated by @markus, you may use the prob argument for this.正如@markus 所指出的,您可以为此使用prob参数。 Here is another idea这是另一个想法

v <- sample(c(sample(1:2, 90, replace = TRUE), sample(3:5, 10, replace = TRUE)))

First generate the 90% (ie here 90 elements) consisting of 1,2 and the remaining 10% (that is 10) separately, and then shuffle the result.首先分别生成由1,2和剩余的10%(即10个)组成的90%(即这里90个元素),然后对结果进行shuffle。

And obviously,而且很明显,

length(which(v %in% 1:2)) / length(v)
# [1] 0.9

Edit编辑

Here the more general case这里是更一般的情况

# size of final vector
n <- 100
# percentages
p1 <- 0.935
p2 <- 1 - p1
# calculate number of elements (using round)
n1 <- round(p1*n)
n2 <- n - n1
# get final vector
v <- sample(c(sample(1:2, n1, replace = TRUE), sample(3:5, n2, replace = TRUE)))

# Note:
length(which(v %in% 1:2)) / length(v)
# [1] 0.94

Note that you could have the exact percentage for example by setting n <- 100*10 .请注意,您可以通过例如设置n <- 100*10来获得确切的百分比。

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

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