Fast way to create a binary matrix with known number of 1 each row in R

前端 未结 4 695
忘了有多久
忘了有多久 2021-01-28 23:10

I have a vector that provides how many \"1\" each row of a matrix has. Now I have to create this matrix out of the vector.

For example, let say I want to create a 4 x 9

4条回答
  •  一个人的身影
    2021-01-29 00:13

    One option is sparseMatrix from Matrix

    library(Matrix)
    m1 <- sparseMatrix(i = rep(seq_along(v), v), j = sequence(v), x = 1)
    m1
    #4 x 9 sparse Matrix of class "dgCMatrix"
    
    #[1,] 1 1 . . . . . . .
    #[2,] 1 1 1 1 1 1 . . .
    #[3,] 1 1 1 . . . . . .
    #[4,] 1 1 1 1 1 1 1 1 1
    

    This can be converted to matrix with as.matrix

    as.matrix(m1)
    

提交回复
热议问题