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

前端 未结 4 2122
粉色の甜心
粉色の甜心 2021-01-15 18:56

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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-15 19:25

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

提交回复
热议问题