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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
ibm
  • 744
  • 7
  • 14
  • 1
    I don't reproduce an error. Could you provide some of your data? Also, note that you don't need to wrap a range of numbers like `1:4` in `c()` because `1:4` is already a vector. – Phil Jul 01 '20 at 17:24
  • It's likely that `as.numeric(Q21) ` returns a value that is not between 1 and 11. It would be easier to help you with a proper [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 01 '20 at 17:27
  • It returns values from 1:12, and 12 just gets recoded as NA (as it should). As I said, the mutate works the way it should, and the fct_relevel does as well, just not when it's piped. I'll update with some reproducable code later tonight. – ibm Jul 01 '20 at 19:33

0 Answers0