unknown2718
unknown2718

Reputation: 11

Getting a fixed number of zeroes randomly in a matrix in R

I have a matrix of size 2000x50. For the 50 places in each of the 2000 rows, I want exactly 6 of them to be 1 and the remaining 44 to be 0. This distribution needs to be random across each row. I have tried using the sample, rbinom functions but none of them seem to be helping. It is also possible that I might not be using them correctly. All thoughts and inputs regarding this will be appreciated.

Thank you.

Edit- Initially I wanted those 6 numbers to be one but now I want them to be sampled randomly from a gamma distribution with both shape and scale= 4. How do I make changes to the suggestions below to incorporate this? I am very new to R and these basic things seem to be troubling me. Thanks once again.

Upvotes: 0

Views: 286

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101189

Based on the approach by @Gki in the comments, you can generate a matrix via replicate + t, i.e.,

m <- t(replicate(2000,sample(rep(0:1, c(44,6)))))

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 173793

This will create the object you requested:

do.call("cbind", lapply(1:2000, function(x) sample(c(rep(1, 6), rep(0, 44))))) 

Upvotes: 3

Related Questions