我正在尝试使用有序的分类变量。似乎最大最小函数应该与有序类别一起使用,但事实并非如此。
var<-factor(c("1","6","4","3","5","2"),levels=c("1","6","4","3","5","2"))
max(levels(var))
我希望代码返回最后一个因子级别(2),但它返回第二个(6)。我究竟做错了什么?在此先感谢您的任何帮助
答案 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