Reordering factor levels

I had used the arrange() function to order my data by two variables (Week, Treatment). Now I would like to change the order in which the Treatment levels are sorted, while retaining the overall grouping by Week. My Treatment column is currently sorted alphabetically and reads:

HQ_HI_D,
HQ_HI_E,
HQ_RI_D,
HQ_RI_E,
HQ_SI_D,
HQ_SI_E,
LQ_HI_D,
LQ_HI_E,
LQ_RI_D,
LQ_RI_E,
LQ_SI_D,
LQ_SI_E

And this then repeats for each week, in ascending week order. For the sake of achieving a certain arrangement of plots in a panel using facet_wrap(), I would like to change the order of Treatment within each week to:

HQ_HI_D,
HQ_HI_E,
LQ_HI_D,
LQ_HI_E,
HQ_SI_D,
HQ_SI_E,
LQ_SI_D,
LQ_SI_E,
HQ_RI_D,
HQ_RI_E,
LQ_RI_D,
LQ_RI_E

Is there a way to reorder the levels while retaining the hierarchy of the arrange function?

Upvotes: 0

Views: 376

Answers (1)

Andrea M
Andrea M

Reputation: 2452

You can use fct_relevel from forcats (documentation):

dat <- dat |> 
  mutate(Treatment = fct_relevel(Treatment, levels = c(
    "HQ_HI_D",
    "HQ_HI_E",
    "LQ_HI_D",
    "LQ_HI_E",
    "HQ_SI_D",
    "HQ_SI_E",
    "LQ_SI_D",
    "LQ_SI_E",
    "HQ_RI_D",
    "HQ_RI_E",
    "LQ_RI_D",
    "LQ_RI_E"
  )))

Then you can use this dataframe in a ggplot.

Data that you provided in the comments - and with arrange():

dat <- structure(list(
        Treatment = c("HQ_HI_D", "HQ_HI_E", "HQ_RI_D",  "HQ_RI_E", "HQ_SI_D", "HQ_SI_E"),
        Week = c(1L, 1L, 1L, 1L, 1L,  1L),
        Mean = c(5.64103269488891, 5.40517308877442, 5.24415513672137,  6.11270063463203, 5.47484895265563, 5.13310791453372),
        SD = c(3.48942634530154,  3.0034679069181, 2.32191693548654, 3.29315597437363, 2.73351044931912,  2.9723575474112)),
        row.names = c(NA, 6L), class = "data.frame") |>
    arrange(Week, Treatment)

Upvotes: 1

Related Questions