0

I've used this successfully, but on a different dataset I'm getting an error of unknown levels in `f`, even though they are basically the same. What is going on? This one works:

df %<>% 
 mutate(
   Education = case_when(
    Education_n %in% c(1:4) ~ "Low", 
    Education_n %in% c(5:8) ~ "Medium", 
    Education_n %in% c(9:11) ~ "High", TRUE ~ NA_character_) %>% fct_relevel("Low", "Medium", "High"))

This one will recode but not relevel, throwing the error. I added as.numeric because this variable is as.character in that dataset. That's the only difference.

dfDDP %<>%mutate( 
    Education = case_when(
      as.numeric(Q21) %in% c(1:4) ~  "Low", #Some secondary
      as.numeric(Q21) %in%  c(5:8) ~  "Medium",
      as.numeric(Q21) %in%  c(9:11) ~ "High", 
      TRUE ~ NA_character_) %>%  fct_relevel("Low", "Medium", "High"))

If I run mutate and fct_relevel separately, it will relevel the way it's supposed to. I've tried %>% fct_relevel("Low", "Medium", "High")), %>% fct_relevel(., "Low", "Medium", "High")), and %>% fct_relevel("High", after = Inf)) without any difference out outcome.

4

0 回答 0