0

I'm trying to recode some factor variables I have, for example:

Apples
Oranges
Cabbage
Broccoli
Cheese

What I'm looking to do is to recode them all so they become Fruit or Non_fruit.

If it is relevant at all, these were recoded earlier on in the script from numeric variables (e.g. 1 = Apples, 2 = Oranges, and so on. I used the exact same argument setup in this as I tried below, but did not get the error and it runs fine.

My argument currently looks like this:

df <- df %>%
dplyr::mutate(
x = recode(x, "Apples" = "Fruit", "Oranges" = "Fruit", .default = "Not_fruit")

The full error is

Error in dplyr::mutate(., diagnosis = recode(x, Apple = "Fruit", : 

ℹ The error occurred in row 1.
Caused by error in `recode()`:
! Argument 2 must be named.

I've also tried using recode_factor, and taking out the inverted commas around the variable (e.g. "Apple") but get the same result, or specifying each variable to recode, but get the same result again.

Would love any feedback or advice anyone may have on this please!

  • You miss a `)` here: `dplyr::mutate( x = recode(x, "Apples" = "Fruit", "Oranges" = "Fruit", .default = "Not_fruit"))` – harre Jul 19 '22 at 12:36
  • Working code in my end: `tibble(x = c("Apples", "Oranges", "Cabbage", "Broccoli", "Cheese")) %>% dplyr::mutate( x = recode(x, "Apples" = "Fruit", "Oranges" = "Fruit", .default = "Not_fruit"))`. If it doesn't work for you, please add an reproducible example based on your real data: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – harre Jul 19 '22 at 12:38
  • If it's a factor variable - and you have many fruits - you might want to use `fct_collapse` for a cleaner look: `fct_collapse(x, Fruit = c("Apples", "Oranges"), other_level = "Not fruit")` – harre Jul 19 '22 at 12:41
  • @harre fct_collapse sorted it, thank you! – Seafra Barrett Jul 19 '22 at 12:58

1 Answers1

1

Try without ":

df <- df %>%
dplyr::mutate(
x = recode(x, Apples = "Fruit", Oranges = "Fruit", .default = "Not_fruit"))

Not teströed from mobile

TarJae
  • 72,363
  • 6
  • 19
  • 66