Sklenicka
Sklenicka

Reputation: 655

R - compare two columns with NAs

I have this dataframe:

    df <- read.table(text="
                 date1       date2
    1            NA          2016-12-01 
    2            2017-01-01  2018-10-01 
    3            2016-12-01  NA 
    4            NA          NA
", header=TRUE)

What I need is to create new "max_date" column which will be containing maximum of date1/date2 columns. Note that at some rows are NA values, in some cases are NA in both columns.

I tried to achieve that with some if_else but code is too complicated. Result should be

    result <- read.table(text="
                 date1       date2         max_date
    1            NA          2016-12-01    2016-12-01
    2            2017-01-01  2018-10-01    2018-10-01
    3            2016-12-01  NA            2016-12-01 
    4            NA          NA            NA
", header=TRUE)

Upvotes: 0

Views: 272

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

You can use pmax:

transform(df, max_date = pmax(as.Date(date1), as.Date(date2), na.rm = TRUE))
#        date1      date2   max_date
# 1       <NA> 2016-12-01 2016-12-01
# 2 2017-01-01 2018-10-01 2018-10-01
# 3 2016-12-01       <NA> 2016-12-01
# 4       <NA>       <NA>       <NA>

Upvotes: 2

Related Questions