Preventing alphabetical sorting in Rstudio

I have data (shown below) I am trying to plot as it is in my excel spreadsheet, but rstudio is automatically sorting it alphabetically which i do not want.
The data:

|Nad_Frequency|Nad_Totals|
|W1|550.6233863|
|W2|553.5625904|
|W3|563.0517622|
|W4|563.6506493|
|W5|566.7065001|
|W6|563.8054161|
|W7|561.7409152|
|M1|572.6378529|
|M2|573.9247763|
|M3|509.9807722|
|M4|561.8506329|
|M5|579.9562373|
|M6|564.9121329|
|M7|592.8302856|
|M8|585.6264275|
|M9|559.6527|
|M10|549.3891637|
|S1|565.1179935|
|S2|566.2964748|
|S3|563.2220424|
|S4|559.6463513|
|S5|562.8478125|
|S6|562.7622964|
|S7|563.8086893|

As you can see the x-axis is sorted alphabetically and so M10 is placed 2nd instead of 10th on the axis. This wouldnt be an issue if it was plotted directly from the spreadsheet data.
Thanks

The reason this is happening is that it is reading the M1, M10, M2 as character values rather than factor variables. Check out the functions as.factor() or as_factor() and you should be able to order them as you please.

You can easily keep current order while converting to factor with fct_inorder(), see this example:

library(tidyverse)

sample_df <- data.frame(
  stringsAsFactors = FALSE,
     Nad_Frequency = c("W1","W2","W3","W4","W5",
                       "W6","W7","M1","M2","M3","M4","M5","M6","M7","M8",
                       "M9","M10","S1","S2","S3","S4","S5","S6","S7"),
        Nad_Totals = c(550.6233863,553.5625904,
                       563.0517622,563.6506493,566.7065001,563.8054161,
                       561.7409152,572.6378529,573.9247763,509.9807722,561.8506329,
                       579.9562373,564.9121329,592.8302856,585.6264275,
                       559.6527,549.3891637,565.1179935,566.2964748,563.2220424,
                       559.6463513,562.8478125,562.7622964,563.8086893)
)

sample_df %>% 
    mutate(Nad_Frequency = fct_inorder(Nad_Frequency)) %>% 
    ggplot(aes(x = Nad_Frequency, y = Nad_Totals)) +
    geom_col()

Created on 2021-08-23 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.