user9292
user9292

Reputation: 1145

maximum date of multiple dates in R

I've three dates d1,d2,d3 (there is a possibility that they could be NA)

id <- c(1,2,3,4,5,6)

d1 <- c("09/30/2000", "","02/30/2000", "05/10/2003", "", "")
d1 <- as.Date(d1, "%m/%d/%y")

d2 <- c("6/30/2014", "6/15/2014","", "8/6/2011", "", "6/30/2014")
d2 <- as.Date(d2, "%m/%d/%y")

d3 <- c("9/5/2015", "9/2/2015","7/5/2015", "", "", "")
d3 <- as.Date(d3, "%m/%d/%y")


    mdata <- data.frame(id,d1,d2,d3)


id  date1   date2   date3
1   9/30/2000   6/30/2014   9/5/2015
2       6/15/2014   9/2/2015
3   02/30/2000      7/5/2015
4   5/10/2003   8/6/2011    
5           
6       6/30/2014   

I need to create a new var "maxdate" which is the max date among d1,d2,d3. If d1 is NA, then maxdate = max(d2,d3). If all d1,d2,d3 are NA, then maxdate=NA.

Here is the output:

id  date1   date2   date3   maxdate
1   9/30/2000   6/30/2014   9/5/2015    9/5/2015
2       6/15/2014   9/2/2015    9/2/2015
3   02/30/2000      7/5/2015    7/5/2015
4   5/10/2003   8/6/2011        8/6/2011
5               NA
6       6/30/2014       6/30/2014

Upvotes: 2

Views: 1490

Answers (2)

Pierre L
Pierre L

Reputation: 28461

Or with apply

mdata$maxdate <- apply(mdata[-1], 1, max, na.rm=T)
#   id         d1         d2         d3    maxdate
# 1  1 2020-09-30 2020-06-30 2020-09-05 2020-09-30
# 2  2       <NA> 2020-06-15 2020-09-02 2020-09-02
# 3  3       <NA>       <NA> 2020-07-05 2020-07-05
# 4  4 2020-05-10 2020-08-06       <NA> 2020-08-06
# 5  5       <NA>       <NA>       <NA>       <NA>
# 6  6       <NA> 2020-06-30       <NA> 2020-06-30

Upvotes: 1

eddi
eddi

Reputation: 49448

mdata$maxdate = Reduce(function(x, y) pmax(x, y, na.rm = T), mdata[,-1])

Upvotes: 1

Related Questions