Mutate error - object not found

I’m trying to change the Gender variable in my dataset to a character variable (i.e., 1 = male, 2 = female, 3 = other)

The code I attempted to run is the following

bwdata6 <- bwdata6 %>% mutate(across(c(Gender),
~recode(.x, ‘1’ = male, ‘2’ = female, ‘3’ = other)))

The error message I got is below.

Error: Problem with mutate() input ..1 .
x object ‘male’ not found
i Input ..1 is across(c(Gender), ~recode(.x, 1 = male, 2 = female, 3 = other)) .

What’s going wrong here?

Without a sample dataset I can't try it, but from what I see, try adding "" to your factor labels i.e. ~recode(.x, ‘1’ = "male", ‘2’ = "female", ‘3’ = "other"))).

Without " " it is trying to search for objects named male, female, and other in your environment.

Consider this example:

df <- data.frame(Gender = c(1, 2, 3, 1), Age = c(59, 69, 79, 89))
df <- as_tibble(df)
df$Gender <- as_factor(df$Gender)

class(df$Gender)
# [1] "factor"
levels(df$Gender)
# [1] "1" "2" "3"
df
# A tibble: 4 x 2
Gender   Age
<fct>  <dbl>
 1 1         59
2 2         69
3 3         79
4 1         89

df <- df %>% mutate(Gender = recode(Gender, `1` = "male", `2` = "female", `3` = "other"))

df
# A tibble: 4 x 2
Gender   Age
<fct>  <dbl>
1 male      59
2 female    69
3 other     79
4 male      89

levels(df$Gender)
# [1] "male"   "female" "other" 

Thanks Bayesian, adding the quotation marks resolved the issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.