Getting index of first occurrence of a value in every column of a matrix

前端 未结 4 1329
野性不改
野性不改 2021-02-02 16:06

If I have a single vector, I can get the 1st occurrence which is below a value:

test <- c(0.5,0.8,0.1,0.08,0.06,0.04)
which(test<0.1)[1]    
4条回答
  •  一整个雨季
    2021-02-02 16:34

    Try this:

    test2 <- matrix(c(5,8,3,4,7,5,6,2),ncol=2)
    > test2
         [,1] [,2]
    [1,]    5    7
    [2,]    8    5
    [3,]    3    6
    [4,]    4    2
    > foo <- function(x){which(x < 5)[1]}
    > apply(test2,2,foo)
    

    The key here being that you take the piece that you know works on a single vector, and simply wrap it in a function. apply will, well, apply that function to each column.

提交回复
热议问题