返回最高水平因子

sla*_*ias 3 refactoring r categories

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

var<-factor(c("1","6","4","3","5","2"),levels=c("1","6","4","3","5","2"))
max(levels(var))
Run Code Online (Sandbox Code Playgroud)

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

Lyz*_*deR 5

只需在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
Run Code Online (Sandbox Code Playgroud)