user1357015
user1357015

Reputation: 11686

Generate a random matrix in R with m columns and n rows where rows sum to 1

I want to generate an nxm matrix. Suppose its 100x3. I want each row to sum to 1 (so two "0"'s and one "1").

sample(c(0,0,1),3) 

will give me 1 row but is there a very fast way to generate the whole matrix without an rbind?

Thank you!

Upvotes: 1

Views: 4221

Answers (4)

Rich Scriven
Rich Scriven

Reputation: 99331

No loops, no transposition. Just create a matrix of zeros and replace one entry per row with 1 by sampling the rows.

m <- matrix(0, 100, 3)
nr <- nrow(m)
m[cbind(1:nr, sample(ncol(m), nr, TRUE))] <- 1

all(rowSums(m) == 1)
# [1] TRUE

Upvotes: 7

Julius
Julius

Reputation: 287

Since you want single 1 for a row, the problem can be restated to select a column entry randomly that has 1 for each row.

So you can do like,

m <- 3; n<-100    
rand_v <- floor(runif(n)*3)+1
mat <- matrix(0,n,m)
idx <- cbind(1:n,rand_v)
mat[idx] <- 1

Hope this helps.

Upvotes: 2

d.b
d.b

Reputation: 32548

 t(apply(t(matrix(rep(c(0,0,1),300),nrow = 3)), 1, function(x) sample(x)))

Upvotes: 2

thc
thc

Reputation: 9705

mat <- matrix(runif(300),ncol=3)
mat[] <- as.numeric(t(apply(mat, 1, function(r) r == max(r))))

Upvotes: 2

Related Questions