[Solved] Fixing r sorting values method


The reason for the observed behavior is the fact, that the factor levels are handled as string. Because of that, the sort is done in an alphabetical order. This results in “100” being before “99” in an ascending order.

The workaround was a bit tricky, I have used the stringr package for easier manipulation of the string. The rest is plain R. There might be more elegant way with dplyr or similar package if you don’t mind the additional dependencies.

Since my edit is not yet visible, here is the data I used as a baseline:

    AWD <- data.frame(
                  name = c("Aaron Donald", "Aaron Rodgers", "Albert Pujols", "Alexis SA¡nchez"),
                  nationality = c("Argentyna", "Brazylia", "Chile", "Dominikana"),
                  discipline = c("Baseball", "Boks", "Formula 1", "Futbol amerykanski"),
                  money = c("41,400,000", "89,300,000", "100,000,000", "30,700,000")) 
    AWD$money <- as.factor(AWD$money)

The solution being this:

    newOrder <- order(as.numeric(str_replace_all(levels(AWD$money), ",","")))
    levels(AWD$money) <- levels(AWD$money)[newOrder]

The str_replace_all is necessary, because R as.numeric doesn’t like the commas in the original values.
After this the plot should work as intended.

Side note:
Working with the original reproducible example was a pain. Please try to cut down the code to the bare minimum next time please.

solved Fixing r sorting values method