返回最高级别因素

时间:2015-10-08 21:54:02

标签: r refactoring categories

我正在尝试使用有序的分类变量。似乎最大最小函数应该与有序类别一起使用,但事实并非如此。

var<-factor(c("1","6","4","3","5","2"),levels=c("1","6","4","3","5","2"))
max(levels(var))

我希望代码返回最后一个因子级别(2),但它返回第二个(6)。我究竟做错了什么?在此先感谢您的任何帮助

1 个答案:

答案 0 :(得分:4)

只需在ordered函数中指定factor参数,然后它就可以了。见如下:

#set the ordered argument to TRUE, so that R understands the order of the levels
#and i.e. which one is min and which is max
var<-factor(c("1","6","4","3","5","2"),levels=c("1","6","4","3","5","2"), ordered=TRUE)

#and then
> max(var)
[1] 2
Levels: 1 < 6 < 4 < 3 < 5 < 2