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

Time:04-29

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!

CodePudding user response:

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

CodePudding user response:

Here is one way:

sapply(d, function(x) which(x==0)[1])
# a b c 
# 4 2 1 

CodePudding user response:

Another possible solution:

apply(d, 2, function(x) which.max(x == 0))

#> a b c 
#> 4 2 1
  • Related