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
>From ?sapply we see that sapply requires a list oratomic vector. If its not a list then looking at the first few two lines of sapply we see it tries to convert the first arg to a list using as.list. Note that using your dt:> as.list(dt)[[1]] [1] -5813 so try this instead: sapply(list(dt), as.character) On 5/20/06, Fernando Saldanha <fsaldan1 at gmail.com> 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 > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html >
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. > > FSDoes 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
?sapply says X: list or (atomic) vector to be used. now dt is neither, and it has been coerced to a list, losing its class. Reading the help page for the function often resolves such questions. On Sat, 20 May 2006, 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"-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595