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

前端 未结 4 678
忘了有多久
忘了有多久 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:11

    vapply is usually faster than sapply. This assigns the desired number of ones to a length-9 vector and then transposes.

    > t( vapply( c(2,6,3,9), function(y) { x <- numeric( length=9); x[1:y] <- 1;x}, numeric(9) ) )
         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    [1,]    1    1    0    0    0    0    0    0    0
    [2,]    1    1    1    1    1    1    0    0    0
    [3,]    1    1    1    0    0    0    0    0    0
    [4,]    1    1    1    1    1    1    1    1    1
    

    Less than 5 seconds on an old Mac.

     system.time( M <- t( vapply( sample(1:500, 100000, rep=TRUE), function(y) { x <- numeric( length=500); x[1:y] <- 1;x}, numeric(500) ) ) )
       user  system elapsed 
      3.531   1.208   4.676 
    

提交回复
热议问题