Dates with foot and articulation

I imported a CSV file with multiple dates and used the as.Date function to convert the date. However, when I use the mapply function to search for the earlier of the two dates, I either end the list with dates or a number vector. How can I get a vector with dates?

POP.Start.final <- mapply(min, combinedOM$Cons.Start.Date.y, combinedOM$OS.Start.Date.y, MoreArgs = list(na.rm=T),SIMPLIFY=T) 

Returns a numeric vector, changing to SIMPLIFY = F returns a list of dates, but I need a date vector.

+4
source share
2 answers

In this particular case, I believe pmin does the trick:

 POP.Start.final <- pmin(combinedOM$Cons.Start.Date.y, combinedOM$OS.Start.Date.y, na.rm=TRUE) 

In general, SIMPLIFY=TRUE (by default) uses the simplify2array utility function to convert lists to atomic mode vectors via as.vector . Since dates are internally stored as numeric, SIMPLIFY=TRUE converts the list of dates to a vector of a numeric number and removes the Date class. You can set SIMPLIFY=FALSE to save the Date class, and then use do.call with c to convert the list to a vector.

 POP.Start.final <- do.call(c,mapply(min, combinedOM$Cons.Start.Date.y, combinedOM$OS.Start.Date.y, MoreArgs = list(na.rm=TRUE),SIMPLIFY=FALSE)) 

Some reproducible codes:

 a <- as.Date(c("2012-01-11","2012-06-30","2012-04-18")) b <- as.Date(c("2013-04-21","2012-03-22","2012-05-01")) pmin(a,b) #[1] "2012-01-11" "2012-03-22" "2012-04-18" do.call(c,mapply(min,a,b,MoreArgs=list(na.rm=TRUE),SIMPLIFY=FALSE)) #[1] "2012-01-11" "2012-03-22" "2012-04-18" 

Aside, using T and F for TRUE and FALSE is a little worrying because T and F can be reassigned until TRUE and FALSE can be reassigned.

+7
source

Not sure if this is the best way, but the origin the as.Date function as.Date January 1, 1970 or 1970-01-01 in the default date format.

So (with compiled data replacing yours), this will work:

 > one <- as.Date("2012-01-01") > two <- as.Date("2012-03-13") > > POP.Start.final <- as.Date( mapply(min, one, two, MoreArgs=list(na.rm=T) ), origin="1970-01-01" ) > str(POP.Start.final) Date[1:1], format: "2012-01-01" 
+1
source

All Articles