Reputation: 71
a few columns of a given data frame are factor level vectors, take one of them as example:
[4661] 12.7 13.2 10.1 12.3
[4665] Not Available 12.7 Not Available Not Available
[4669] Not Available Not Available Not Available 11.1
[4673] 9.9 9 Not Available 9.7
[4677] 8.9 10.1 11.7 13
[4681] Not Available 11.5 Not Available Not Available
[4685] 12.3 11.2 Not Available 11.1
[4689] 10.4 Not Available Not Available Not Available
[4693] 11.5 Not Available Not Available Not Available
[4697] Not Available Not Available 12 Not Available
[4701] Not Available Not Available Not Available Not Available
[4705] Not Available Not Available
106 Levels: 10 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 ... Not Available
I find it annoying that it keeps saying the 106 levels start from 10 then 10.1, but in fact there are many values below 10, as shown in the above list.
How do I fix this, and have levels automatically match all values? Thanks.
Upvotes: 0
Views: 1217
Reputation: 93813
You can change the order to numeric order with some re-factor
-ing
x <- factor(c(10,10.1,10.2,9,8,1,"Not available"))
levels(x)
#[1] "1" "10" "10.1" "10.2"
#[5] "8" "9" "Not available"
factor(x, levels=levels(x)[order(as.numeric(as.character(levels(x))),na.last=TRUE)])
#[1] 10 10.1 10.2 9 8 1 Not available
#Levels: 1 8 9 10 10.1 10.2 Not available
Arguably you should just be using this data as numeric in the first place, like:
as.numeric(as.character(x))
#[1] 10.0 10.1 10.2 9.0 8.0 1.0 NA
Upvotes: 1