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

前端 未结 4 1330
野性不改
野性不改 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:21

    As noted by Matthew, which.max does not return the correct value if there's no value <5 in a column (it returns 1, whereas the correct value is "nothing"). The match function is nice to handle this case:

    > test2 <- matrix(c(5,8,3,4, 7,5,6,7), ncol=2)
    > apply(test2<5, 2, which.max)
    [1] 3 1
    > apply(test2<5, 2, function(x) match(TRUE, x))
    [1]  3 NA
    

提交回复
热议问题