Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disabling mapply automatically converting Dates to numeric

Tags:

r

I've noticed that when you do this:

mapply(function(x) { x }, c(as.Date('2014-1-1'), as.Date('2014-2-2')))

R automatically converts your vector of Dates into a vector of numbers. Is there a way to disable this behavior?

I know that you can wrap the result in as.Date(..., origin='1970-1-1'), but I can only imagine there has to be a better solution here.

like image 856
chuck taylor Avatar asked Dec 17 '14 22:12

chuck taylor


1 Answers

This has to do with the way mapply simplifies its result through simplify2array.

x <- list(as.Date('2014-1-1'), as.Date('2014-2-2'))
simplify2array(x, higher = FALSE)
# [1] 16071 16103

You can turn off the simplification and then reduce the list manually.

do.call(c, mapply(I, x, SIMPLIFY = FALSE))
# [1] "2014-01-01" "2014-02-02"

Or you can use Map along with Reduce (or do.call)

Reduce(c, Map(I, x))
# [1] "2014-01-01" "2014-02-02"

Map is basically mapply(..., SIMPLIFY = FALSE) and I use I in place of function(x) { x } because it just returns its input as-is.

like image 77
Rich Scriven Avatar answered Oct 22 '22 21:10

Rich Scriven