简体   繁体   English

如何从R中的随机数生成器指定奇数和偶数的数量?

[英]How to specify the number of odd and even numbers from a random generator in R?

I need to generate a random selection of 9 whole numbers from 1 to 40 with the following condition: the output must contain 5 even numbers and 4 odd numbers. 我需要在以下条件下从1到40生成9个整数的random选择:输出必须包含5个even和4个odd

I have the following code to generate 9 random numbers: 我有以下代码来生成9个随机数:

x1<- sample(1:40, 9, replace=F)
> x1
  [1]  2 36  6 10 39 17 14 11 25

I now need to add the odd and even numbers condition in the equation. 现在,我需要在方程式中添加奇数和偶数条件。 How can I do this? 我怎样才能做到这一点?

Assuming the order of the numbers does not matter, you could try 假设数字的顺序无关紧要,您可以尝试

c(sample(seq(2,40,by=2), 5, replace=F), sample(seq(1,39,by=2), 4, replace=F))

where seq(2,40,by=2) generates the even numbers, and seq(1,39,by=2) generates the odd numbers. 其中seq(2,40,by=2)生成偶数,而seq(1,39,by=2)生成奇数。 If the order does matter (ie it should also be random), you can wrap the outer c with sample : 如果顺序确实很重要(即也应该是随机的),则可以用sample包裹外部c

sample(c(sample(seq(2,40,by=2), 5, replace=F),sample(seq(1,39,by=2), 4, replace=F)))

Hope this helps! 希望这可以帮助!

您可以尝试以下方法:

sample(c(2*sample(0:19, 4) + 1, 2*sample(1:20, 5)))

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

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