slap-a-da-bias
slap-a-da-bias

Reputation: 406

return the highest level factor

I'm trying to work with an ordered categorical variable. It seems like the max min functions should work with the ordered categories, but it doesn't.

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

I'd like the code to return the very last factor level (2), but it returns the second (6). What am I doing wrong? Thanks in advance for any help

Upvotes: 6

Views: 7809

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

Just specify the ordered argument in the factor function and then it will work. See following:

#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

Upvotes: 14

Related Questions