Search code examples
rmatrixrow

How can I know the number of the row that has specific conditions? In R


I have this dataframe:

d <- structure(list(a = c(1, 66, 58, 0, 91, 37), b = c(44, 0, 75, 
11, 0, 32), c = c(0, 81, 0, 53, 25, 13)), class = "data.frame", row.names = c(NA, 
-6L))

I need to know, for each column, the position (row number) of the first zero. In this case the result should be

4, 2, 1

How can I do? Thx for help!


Solution

  • You can use max.col:

    max.col(t(d) == 0, "first")
    

    If you only have positive values, you can also do:

    sapply(d, which.min)
    # [1] 4 2 1