2

Quick question: In R, how to generate a random binary vector of fixed length with fixed sum.

For example:

I want a binary vector of length 100 that sum up to 15.

Thanks!

1
  • 2
    Numerous ways, including sample(c(rep(1,15),rep(0,85))) Commented Jun 29, 2021 at 20:24

2 Answers 2

1

You could write a function for this:

rand_binary <- function(n,k){
  v <- numeric(n)
  v[sample(seq_along(v),k)] <- 1
  v
}

And then rand_binary(100,15) evaluates to a randomly chosen vector consisting of 85 0s and 15 1s.

Sign up to request clarification or add additional context in comments.

Comments

0

We can do something like below

replace(rep(0, 100), sample(100, 15), 1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.