R:'因素'可能存在错误?

时间:2013-07-12 12:01:55

标签: r date r-factor

这可能是factor中的错误还是我在这里遗漏了什么?

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

1 个答案:

答案 0 :(得分:2)

这是因为因子级别为character s,而xxDate。将character向量传递给levels参数可以按预期工作:

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