Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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!
sample(c(rep(1,15),rep(0,85)))
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.
rand_binary(100,15)
Add a comment
We can do something like below
replace(rep(0, 100), sample(100, 15), 1)
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
sample(c(rep(1,15),rep(0,85)))