Question

Is this a possible bug in factor or am I missing something here?

xx <- seq.Date(Sys.Date(), length.out=5, by="1 day")

factor(xx) # Works fine!
[1] 2013-07-12 2013-07-13 2013-07-14 2013-07-15 2013-07-16
Levels: 2013-07-12 2013-07-13 2013-07-14 2013-07-15 2013-07-16

factor(xx, levels=unique(xx)) # Generates NAs.
[1] <NA> <NA> <NA> <NA> <NA>
Levels: 2013-07-12 2013-07-13 2013-07-14 2013-07-15 2013-07-16
Was it helpful?

Solution

It is because factor levels are characters, while xx is Date. Passing a character vector to the levels argument works as expected:

factor(xx, levels=as.character(unique(xx)))
[1] 2013-07-12 2013-07-13 2013-07-14 2013-07-15 2013-07-16
Levels: 2013-07-12 2013-07-13 2013-07-14 2013-07-15 2013-07-16
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top