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

Multi tool use


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.
random
even
odd
I have the following code to generate 9 random numbers:
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?
2 Answers
2
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. If the order does matter (i.e. it should also be random), you can wrap the outer c
with sample
:
seq(2,40,by=2)
seq(1,39,by=2)
c
sample
sample(c(sample(seq(2,40,by=2), 5, replace=F),sample(seq(1,39,by=2), 4, replace=F)))
Hope this helps!
When running the codes where order matters, I get the following error message: Error in sample.int(length(x), size, replace, prob) : cannot take a sample larger than the population when 'replace = FALSE'
– user3115933
4 mins ago
@user3115933 oops, my bad! Fixed it ;) I replaced
c
instead of wrapping it.– Florian
3 mins ago
c
You could try this:
sample(c(2*sample(0:19, 4, replace=FALSE) + 1, 2*sample(1:20, 5, replace=FALSE)))
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
@G5W That's a good idea, I did not think of that. Added that to the solution.
– Florian
8 mins ago