[R] Casting "character" to "Date" using the "as" function

david.schruth dschruth at gmail.com
Tue Feb 23 20:18:54 CET 2010


Hello,

I'm trying to write a function which, among other things, attempts to
convert variables of type 'character' into various other classes like
'integer', 'numeric', 'character' & "Date", depending on the class of
a second parameter to this same function.   Converting from character
to Date is no problem with the "as.Date" function:

> date.var.char <- as.character("2009-10-21")
> as.Date(date.var.char)
 [1]  "2010-02-23"

But when I try to do the equivalent using just "as" I get an error

> date.var.Date <- as.Date("2009-10-21")
> as(date.var.char,   class(date.var.Date))
 Error in as("2009-10-21", "Date"): no method or default for coercing
"character" to "Date"

The same is true for POSIXt, POSIXlt, & POSIXct

Is there something that I can do without writing those extra 2 lines
of code to check and see if 'date.var.Date' is actually of the 'Date'
class? Or is this a bug?

Thanks,

Dave



More information about the R-help mailing list