Reorder factors numerically in a data frame

If all the integers are present, then you can simply use order:

  order(levels(items$label)) - 1   # where the minus 1 is for starting from 0

If not all integers are present, then you have to use as.numeric, like you have it.


sorted_labels <- paste(sort(as.integer(levels(items$label))))

Gives:

 [1] "0"  "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11"
[13] "12" "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23"
[25] "24" "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35"
[37] "36" "37" "38" "39"

Or (as mentioned in https://stackoverflow.com/a/15665655/109618):

sorted_labels <- order(levels(items$label)) - 1
# order by itself is a 1-based vector
# using `- 1` gives a 0-based vector

Per the updated question, this updates the data frame:

items$label <- factor(items$label, levels = sorted_labels)

Tags:

Sorting

R