I have a data.frame in which one of the columns, originally containing integer values, was converted to a factor (upstream of any data that I have).
I'd like to sort the data.frame based on this factor, but have the results sorted such that the order of this factor is "1 2 3" instead of "1 11 12," as is what happens when I use order
with no other manipulations:
sample <- data.frame(a = c(1,2,2,3,4), b= factor(c("1","12","11","2","3")))
sample
a b
1 1 1
2 2 12
3 2 11
4 3 2
5 4 3
sample[order(sample$b),]
a b
1 1 1
3 2 11
2 2 12
4 3 2
5 4 3
Since I want that column to remain a factor in my final dataset, I am hesitant to convert the column to an integer (because of issues with as.integer
and as.numeric
when applied to factors). I also have nearly 100 levels in this factor, so manually redefining the levels of the factor in a way that requires me to write out each level is not ideal either.