Varun
Varun

Reputation: 1321

R Generate random numbers based on condition

I'd like to generate a sequence of 100 numbers based on the following conditions -

My Attempt

I attempted to create the sequence using 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

Upvotes: 2

Views: 1391

Answers (1)

niko
niko

Reputation: 5281

As indicated by @markus, you may use the prob argument for this. Here is another idea

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

First generate the 90% (i.e. here 90 elements) consisting of 1,2 and the remaining 10% (that is 10) separately, and then shuffle the result.

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.

Upvotes: 1

Related Questions