user1134616 user1134616 - 2 months ago 19
R Question

Error with class(charactervector) <- "Date"

The following does not work:

today <- as.character("2016-09-13")
class(today) <- 'Date'

today
## [1] NA



Warning messages:

1: In as.POSIXlt.Date(x) : NAs introduced by coercion

2: In as.POSIXlt.Date(x) : NAs introduced by coercion

3: In as.POSIXlt.Date(x) : NAs introduced by coercion
as.numeric(a)



Whereas this does work:

today <- as.character("2016-09-13")
a <- as.Date(today)

a
## [1] "2016-09-13"

as.numeric(a)
## [1] 17057


I'd like to have the a solution to make
class(today) <- 'Date'
work and understand why it is not working.

Answer

The class<- function does not trigger any conversion/coercion code. The class<- function maps to the R_do_set_class function in C code. And ultimately you wind up at a code branch where they explicitly don't do the coercion.

Look at these two examples

today <- as.character("2016-09-13")
class(today) <- 'Date'
dput(today)
# structure("2016-09-13", class = "Date")

today<-as.Date("2016-09-13")
dput(today)
# structure(17057, class = "Date")

Notice how an S3 "class" is just a named attribute on a structure in R. It tells R how to interpret the value in that structure. If you manually set the class to something incompatible with the value (as you might do with class<-), you run the risk of breaking things.

Also notice that you don't get the error unless you try to print the value of today. That's because the re-assignment "works" but when R goes to use the value (as when printing), things get messed up because it's not stored in the way R expect.,

The lesson really is that class<- should not be used for conversion between different class. It it only use to fiddle with the class attribute of an object.