[R] sapply and Date objects

Marc Schwartz MSchwartz at mn.rr.com
Sat May 20 17:26:11 CEST 2006


On Sat, 2006-05-20 at 11:01 -0400, Fernando Saldanha wrote:
> This is probably a dumb question, but I cannot figure it out. Why does
> this happen?
> 
>  dt <- as.Date("1954-02-01")
> > as.character(dt)
> [1] "1954-02-01"
> > sapply(c(dt), as.character)
> [1] "-5813"
> 
> Thanks.
> 
> FS

Does this help?

> dt <- as.Date("1954-02-01")

> dt
[1] "1954-02-01"

# Note the numeric value of dt is an offset from the default
# base date in R of 1970-01-01
> str(dt)
Class 'Date'  num -5813

> dt + 5813
[1] "1970-01-01"


When using sapply(), the 'X' argument is first coerced to a list which
is then passed to lapply(). So:

> as.list(dt)
[[1]]
[1] -5813


> str(as.list(dt))
List of 1
 $ : num -5813


Note that the result of the coercion to a list loses the Date class
attribute. Thus, you end up with just a numeric value, which you are
then coercing to a character vector.

So, in effect you are doing:

> unlist(lapply(as.list(dt), as.character))
[1] "-5813"


HTH,

Marc Schwartz



More information about the R-help mailing list