创建月份矢量。
> mths<-month.abb
> mths
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
但这是字符向量,因此我将其转换为如下因素:
> mths1<-factor(mths)
> mths1
[1] Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Levels: Apr Aug Dec Feb Jan Jul Jun Mar May Nov Oct Sep
但现在水平的顺序显示为字母,这不是我们想要的。尝试以下操作,我们按正确顺序获取级别,但数据混乱。
> levels(mths1)<-mths
> mths1
[1] May Apr Aug Jan Sep Jul Jun Feb Dec Nov Oct Mar
Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
然后我尝试了这个:
> mths1[]<-mths
> mths1
[1] Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
现在这些因素及其等级都正确排序。
我想知道在上述每种情况下幕后发生的动态是什么,因为对关卡和数据的分配让我有点困惑。
最后,什么是更优雅的方式来实现同样的目标?
答案 0 :(得分:2)
将上述评论合并到答案中
mths<-month.abb
mths
# [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
mths1 <-factor(mths, levels=mths, ordered=TRUE)
mths1
# [1] Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
# Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec