user1134616 user1134616 - 1 year ago 115
R Question

Error with class(charactervector) <- "Date"

The following does not work:

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

## [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

Whereas this does work:

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

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

## [1] 17057

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

Answer Source

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'
# structure("2016-09-13", class = "Date")

# 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download