Daniel Estabrook Daniel Estabrook - 1 year ago 42
R Question

new variable lesser of two dates in R

I have two columns of dates. The first column occasionally has blanks. I want to create a new variable that returns the maximum date for that row from either column.

date2<-c("23-01-08", "01-11-07","29-11-07","19-12-07","12-12-08")
df<-data.frame(date1, date2) df$date1<-as.Date(date1, format =
"%d-%m-%y") df$date2<-as.Date(date2, format = "%d-%m-%y")
df$mindate<-pmin(df, date1, date2, na.rm = TRUE)

Currently the last line gives me an error:

In pmin(df, date1, date2, na.rm = TRUE) :
an argument will be fractionally recycled

And the resultant dataframe has no data.


Answer Source

The pmin doesn't work like with

pmin(df$date1, df$date2, na.rm = TRUE)
#[1] "2008-01-23" "2007-11-01" "2007-11-29" "2007-12-17" "2008-12-12"


with(df, pmin(date1, date2,  na.rm = TRUE))
#[1] "2008-01-23" "2007-11-01" "2007-11-29" "2007-12-17" "2008-12-12"

Or more compactly

do.call(pmin, c(df, na.rm = TRUE))
#[1] "2008-01-23" "2007-11-01" "2007-11-29" "2007-12-17" "2008-12-12"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download