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
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