rforcatsnegate

negating levels for fct_collapse


I have a smaller list of levels that should not be collapsed ("Alberta", "British Columbia", "Ontario", "Quebec") than the ones that should (all else). I haven't been able to negate the levels (code as example of the goal) for fct_collapse (all but the following). Any suggestions?

df$`Province group` %<>% fct_collapse(df$Province, `Smaller provinces` = !c("Alberta", "British Columbia", "Ontario", "Quebec"))


Solution

  • fct_lump was the best solution for this problem (only because the logic of the question was to negate the 4 large-n provinces). If anyone finds a shorter solution than Rui Barradas I'd still be interested for future factor work.

    df%>%
      mutate(`Compared to smaller provinces` = fct_lump(Province, n = 4)) %>%
      count(`Compared to smaller provinces`)
    

    This produces 5 groups where "other" is all the other smaller-n response provinces.