Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reordering levels of a factor by group in R

I have a dataframe:

example <- data.frame(
  subject = c(rep(101,12),
              rep(102,12)),
  conditions = rep(c("selfimmneg", "selfimmneut", "selfrefneg", "socimmneg", "socimmneut", "socrefneg"), 4)
)

example$conditions <- as.factor(example$conditions)

I want to reorder the levels within conditions by subject, such that the same levels are grouped together in this order: "selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut" by subject.

This is the desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

example_solution <- data.frame(
  subject = c(rep(101,12),
              rep(102,12)),
  conditions = rep(rep(c("selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut"), each = 2),2)
)

How can I do this?

Thank you!

>Solution :

One way is to use fct_relevel:

library(forcats)
library(dplyr)

# your order
order <- c("selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut")

example %>%
  mutate(conditions = fct_relevel(conditions, order)) %>%
  arrange(subject, conditions)

  subject  conditions
1      101  selfrefneg
2      101  selfrefneg
3      101  selfimmneg
4      101  selfimmneg
5      101 selfimmneut
6      101 selfimmneut
7      101   socrefneg
8      101   socrefneg
9      101   socimmneg
10     101   socimmneg
11     101  socimmneut
12     101  socimmneut
13     102  selfrefneg
14     102  selfrefneg
15     102  selfimmneg
16     102  selfimmneg
17     102 selfimmneut
18     102 selfimmneut
19     102   socrefneg
20     102   socrefneg
21     102   socimmneg
22     102   socimmneg
23     102  socimmneut
24     102  socimmneut
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading