0

I have a dataframe which consists of several columns in the Date format. I would like to extract the column name of the earliest date per row. Is this possible?

davidbuis
  • 11
  • 3
  • 1
    Yes, it is possible. If I were doing it, I would use `pivot_longer()` from the `tidyr` package and then do the operations in long form. I can be more precise if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – DaveArmstrong May 26 '23 at 13:19

1 Answers1

0

You will need some way to handle the case when the earliest date appears in more than one column. Here is an example where we have unique minima, which will hopefully get you started.

## prepare sample data
set.seed(123)
n = 10
df = data.frame(
    date1 = Sys.Date() + runif(n)*20,
    date2 = Sys.Date() + runif(n)*20,
    date3 = Sys.Date() + runif(n)*20
)

## add a column showing the name of the variable with the earliest date
df$earliest = apply(df, 1, function(x) {
    names(x)[which(x == min(x))]
})

Output:

        date1      date2      date3 earliest
1  2023-05-31 2023-06-14 2023-06-12    date1
2  2023-06-10 2023-06-04 2023-06-08    date2
3  2023-06-03 2023-06-08 2023-06-07    date1
4  2023-06-12 2023-06-06 2023-06-14    date2
5  2023-06-13 2023-05-28 2023-06-08    date2
6  2023-05-26 2023-06-12 2023-06-09    date1
7  2023-06-05 2023-05-30 2023-06-05    date2
8  2023-06-12 2023-05-26 2023-06-06    date2
9  2023-06-06 2023-06-01 2023-05-31    date3
10 2023-06-04 2023-06-14 2023-05-28    date3
BigFinger
  • 1,033
  • 6
  • 7
  • Thanks! The problem is that the minima are not unique. Is there a solution for this? For example, returning date1 + date2 if both are equal? – davidbuis May 30 '23 at 08:10
  • If minima are not unique, the code will still work, but the elements of column "earliest" will be lists. Try setting n=20 in the sample code to see the behavior. If you want strings instead, you can collapse the lists by replacing "names(x)..." with "paste(names(x)..., collapse=' + ')". – BigFinger May 30 '23 at 15:29