Diego
Diego

Reputation: 93

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

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.

Upvotes: 3

Views: 1508

Answers (4)

akrun
akrun

Reputation: 887501

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]

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 102241

Another base R option

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

which gives

[1] 1996

Upvotes: 3

heds1
heds1

Reputation: 3448

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
)

Upvotes: 4

Frank
Frank

Reputation: 66819

If your A is nonnegative

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

Upvotes: 5

Related Questions