返回最高级别因子

5

我试图使用有序分类变量。看起来max和min函数应该适用于有序类别,但实际上并不是这样。

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

我希望代码能返回最后一个因子水平(2),但它返回了第二个(6)。我做错了什么?感谢您提前的帮助。

1
6是最大值。而你正在请求它。也许是tail命令? - user3710546
1
levels(var)[max(as.numeric(var))] 返回 [1] "2"。顺便说一下,你的因子在 R 中并没有被排序。 - Pierre L
6 是数字上限,但当我在命令的“levels”部分指定顺序时,我认为它会输出最后一级(2)。 - slap-a-da-bias
@Pierre Lafortune - 我该如何在 R 中对水平进行排序? - slap-a-da-bias
@LyzandeR,你删除了你的回答。 - Pierre L
显示剩余3条评论
1个回答

12

只需要在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

哇,这真是令人惊讶的 +1!你知道 max 在因子上的文档在哪里吗?我看到它说它们是通用函数,但是否有 max.factormax.ordered... - Rorschach
@bunk,我在文档中找不到关于max的任何信息,但你可以在?factor中找到相关信息。因素本质上是后台整数,如果它们被排序,则会为它们的级别分配有序整数。这就是max理解哪个元素实际上是最大值的方式。 - LyzandeR
我现在正在阅读相关内容,如果你查看?Summary。我甚至不知道这个groupGeneric的东西存在 :D - Rorschach
@bunk 是的,它确实有:)。我认为没有 max.factormax.ordered - LyzandeR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接