How to vectorize this operation on every row of a matrix

前端 未结 3 615
醉酒成梦
醉酒成梦 2021-01-20 13:59

I have a matrix filled with TRUE/FALSE values and I am trying to find the index position of the first TRUE value on each row (or retur

3条回答
  •  心在旅途
    2021-01-20 14:39

    You can gain a lot of speed by using %% and %/%:

    x <- matrix(rep(c(F,T,T),10), nrow=10)
    
    z <- which(t(x))-1
    ((z%%ncol(x))+1)[match(1:nrow(x), (z%/%ncol(x))+1)]
    

    This can be adapted as needed: if you want to do this for columns, you don't have to transpose the matrix.

    Tried out on a 1,000,000 X 5 matrix :

    x <- matrix(sample(c(F,T),5000000,replace=T), ncol=5)
    
    system.time(apply(x,1,function(y) which(y)[1]))
    
    #>   user  system elapsed 
    #>  12.61    0.07   12.70 
    
    system.time({
     z <- which(t(x))-1
     (z%%ncol(x)+1)[match(1:nrow(x), (z%/%ncol(x))+1)]}
    )
    
    #>   user  system elapsed 
    #>   1.11    0.00    1.11 
    

    You could gain quite a lot this way.

提交回复
热议问题