5

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.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
chuck taylor
  • 2,476
  • 5
  • 29
  • 46
  • side note : You should maybe rewrite your code example , this is not the right way to use `mapply`. – agstudy Dec 17 '14 at 23:14
  • I'm not sure exactly what you mean. – chuck taylor Dec 17 '14 at 23:28
  • I mean that the usual way to use `mapply` is `mapply(function(x,y),X,Y)` for example `mapply(rep, 1:4, 4:1)`. You are using it as `sapply/lapply`. As I already mentioned this only a side note. – agstudy Dec 17 '14 at 23:34

1 Answers1

6

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.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245