How to vectorize this operation on every row of a matrix

前端 未结 3 635
醉酒成梦
醉酒成梦 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:36

    Not sure this is any better, but this is one solution:

    > x2 <- t(t(matrix(as.numeric(x), nrow=10)) * 1:3)
    > x2[x2 == 0] <- Inf
    > rowMins(x2)
     [1] 2 1 1 2 1 1 2 1 1 2
    

    Edit: Here's a better solution using base R:

    > x2 <- (x2 <- which(x, arr=TRUE))[order(x2[,1]),]
    > x2[as.logical(c(1,diff(x2[,1]) != 0)),2]
     [1] 2 1 1 2 1 1 2 1 1 2
    

提交回复
热议问题