简体   繁体   English

R-比较两列与NA

[英]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. 我需要创建新的“ max_date”列,其中将包含最大的date1 / date2列。 Note that at some rows are NA values, in some cases are NA in both columns. 请注意,在某些行中是NA值,在某些情况下,两列中都是NA。

I tried to achieve that with some if_else but code is too complicated. 我试图用一些if_else来实现,但是代码太复杂了。 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)

You can use pmax : 您可以使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM