Recoding Categorical Variable

I have a mutated categorical variable to perform an ANOVA. It is a factor with 6 levels. I am trying to make those 6 levels be only 2 levels: "Low" and "High" or 1 and 2.

sleepdata_complete <- mutate(sleepdata_complete,
qualslp = as.factor(qualslp),
qualslp = fct_recode(qualslp,
"V Poor" = "1",
"Poor" = "2",
"Fair" = "3",
"Good" = "4",
"V Good" = "5",
"Excel" = "6"))

This is what I currently have. Is there any way to change this? thank you!

Hi, you could use case_when. It would be something like this. To make it easier for everyone, you should provide a reproducible example next time.

library(dplyr)

sleepdata_complete <- mutate(sleepdata_complete,
                             qualslp = as.factor(qualslp),
                             qualslp2 = case_when(qualslp %in% c("V Poor", "Poor", "Fair") ~ "Low",
                                                  TRUE ~ "High")) %>%
  mutate(qualslp2 = factor(qualslp2, levels = c("Low", "High")))
  

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.