Biru
Biru

Reputation: 25

generate a vector between 0 and 1, with certain length and certain number of 1

I need to create a vector of length 4, such that 2 of the elements are 1, the other 2 are 0, and which number appears in a certain place is random.

For example, the first simulation is [1, 1, 0, 0]. The second simulation might be [1, 0, 1, 0] or something else.

I tried the code as follows:

 sample(x = c(0,1), size = 4, replace = TRUE, prob = 0.5)

but it simply returned a list with random numbers of 1 and 0.

Is it possible to make such a list without using for or while loops?

Upvotes: 2

Views: 657

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

You can give two values for prob argument but this doesn't guarantee the distribution to be equal

sample(x = c(0,1), size = 4, replace = TRUE, prob = c(0.5, 0.5))
#[1] 1 0 0 1
sample(x = c(0,1), size = 4, replace = TRUE, prob = c(0.5, 0.5))
#[1] 1 1 0 1
sample(x = c(0,1), size = 4, replace = TRUE, prob = c(0.5, 0.5))
#[1] 0 0 0 1

What you can do instead is create your vector using rep and then use sample for randomness

sample(rep(c(1, 0), 2))
#[1] 0 1 0 1

sample(rep(c(1, 0), 2))
#[1] 0 0 1 1

sample(rep(c(1, 0), 2))
#[1] 1 1 0 0

sample(rep(c(1, 0), 2))
#[1] 0 1 1 0

This would also work if you have different vector length as we can use the times argument

n <- 11

sample(rep(c(0, 1), c(n - 3, 3)))
#[1] 0 0 1 0 1 1 0 0 0 0 0
sample(rep(c(0, 1), c(n - 3, 3)))
#[1] 0 1 0 0 0 0 1 0 0 0 1
sample(rep(c(0, 1), c(n - 3, 3)))
#[1] 0 1 0 0 0 0 1 0 0 0 1

Upvotes: 3

Related Questions