Find position of first value greater than 0 in column A and return value in that position in column B

Viewed 636

I'm new in R and I'm struggling with this problem: I want to evaluate values in column A and get the position of the first non-zero value in that column. Then, I want to obtain the value in the position found but in column B. This would need to happen in a data frame similar to this one.

Column A Column B
0 1998
0 1997
2 1996
3 1995

So the output should be: 1996.

I've tried using match() without success. Thank you in advance.

4 Answers

If your A is nonnegative

B[ match(FALSE, cummax(A) == 0) ]

We can use base R functions i.e. with - create a logical condition with 'Column A', subset the corresponding elements of 'Column B' where the logical condition is TRUE, and use indexing [1] to return the first element

with(df1, `Column B`[`Column A` > 0][1])

If the column name is stored in another object

obj1 <- 'Column A'
df1[["Column B"]][df1[[obj1]] > 0][1]

The existing answers are both great. Just thought I'd round this out with a tidyverse method that's quite readable:

library(dplyr)

dat %>%
    filter(`Column A` > 0) %>%
    slice(1) %>%
    pull(`Column B`)

Data:

dat <- tribble(
    ~`Column A`, ~`Column B`,
    0,         1998,
    0,         1997,
    2,         1996,
    3,         1995
)

Another base R option

with(
  df,
  ColumnB[which.min(ColumnA <= 0)]
)

which gives

[1] 1996
Related