Random binary matrix with row and column sum constraints

限于喜欢 提交于 2019-12-06 02:25:57

I found the sparseMatrix in the Matrix library, but it wants a vector or row indices and another vector of column indices, which is not what I have.

The constraints impose that...

  • row indices are rep(1:4, 6)
  • col indices are 1:24

The match between row and col indices is randomized. We can...

library(Matrix)

# fix rows, jumble cols
sparseMatrix(rep(1:4, each=6), sample(1:24))

# fix cols, jumble rows
sparseMatrix(sample(rep(1:4, each=6)), 1:24)

# jumbl'm all
sparseMatrix(sample(rep(1:4, each=6)), sample(1:24))

any of which will return something like

4 x 24 sparse Matrix of class "ngCMatrix"

[1,] . . . . | | . . | . . . | | . | . . . . . . . .
[2,] . | | . . . | . . | . . . . . . . . | . . . | .
[3,] . . . | . . . | . . | | . . . . | . . . | . . .
[4,] | . . . . . . . . . . . . . | . . | . | . | . |
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!