0

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)))
Lenman55
  • 27
  • 4
  • 4
    What exactly didn't work out with the `across` stuff? Did you get specific errors? It's easier to help you if you include a simple [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 May 31 '23 at 17:58
  • Thanks for your quick reply. I added my code snippet – Lenman55 May 31 '23 at 18:07
  • 4
    Thanks for adding the code snippet, but it's still not a reproducible example. You could make a tiny reproducible example with (say) 3 factors with 3 levels each so we could play with it ... – Ben Bolker May 31 '23 at 18:10
  • 2
    Instead of `mutate(across(where(is.factor), ~ fct_recode(., !!!level_mapping)))` use `mutate(across(where(is.factor), ~ recode(., !!!level_mapping)))` – TarJae May 31 '23 at 18:11
  • I added one now. Hope it helps and thanks again – Lenman55 May 31 '23 at 18:42
  • 1
    What happens when you try @TarJae's comment with your real data? (It works for me.) – r2evans May 31 '23 at 19:02

1 Answers1

3

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Works for me too! Also noticed some problems in my dataframe I was able to fix. Thank you very much – Lenman55 May 31 '23 at 19:08