rdplyrtidyversedata-wranglingr-factor

How to change the levels of multiple factors at once


G'day, I have a data frame with multiple factor variables.

I want to change the levels of all those factors variables to the same of levels. They have all have 16 levels, which i would want to change to 7.

It already works for me if i to it like this:

data <-
data |>
  mutate(variable = fct_recode(
  variable,
    "new level" = "old level",
     "…"   = "…"
    "new level" = "old level"))

And this I could do for every single factor.

But since I have about 19 other factors I would prefer to do it with less boiler plate and not one for one.

So i am basically looking for a way to change the levels of all 19 factors at once

I tried some across()-stuff, but it did not quite worked out.

 level_mapping <- c(
  "new level" = "old level",
  "..." = "..."
  "new level" = "old level")

df_new <- df_old %>%
  mutate(across(where(is.factor), ~ fct_recode(., !!!level_mapping)))

I hope my question is understandable and any help would be appreciated

[Edit] I forgot to mention: While changing the factor levels, I would also like to drop one of them An repex:

library(dplyr)
df <- data.frame(
  var1 = factor(c("A", "B", "C")),
  var2 = factor(c("A", "B", "C")),
  var3 = factor(c("A", "B", "C"))
)

level_mapping <- c(
  "A" = "R",
  "B" = "E",
  "C" = "F")

df_new <- df %>%
  mutate(across(where(is.factor), ~ recode(., !!!level_mapping))), "F" = NA)))

Solution

  • This code runs for me

    df %>%
      mutate(across(where(is.factor), ~ recode(., !!!level_mapping, "F" = NA_character_)))
    

    Recode was complaining about the NA value at first, but I changed it to use the strongly typed NA value. And mostly getting things to work just involved moving the parenthesis to the correct place.