return最高等级因子

return the highest level factor

我正在尝试使用有序分类变量。似乎 max min 函数应该适用于有序类别,但事实并非如此。

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

我想要 return 最后一个因子级别 (2) 的代码,但 return 是第二个 (6)。我究竟做错了什么?在此先感谢您的帮助

只需在 factor 函数中指定 ordered 参数即可。请参阅以下内容:

#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