How to Recode a Column with dplyr in R?

I was trying to recode a column with two values using dplyr.

name <- c("John", "Clara", "Smith")

sex <- c(1,2,1)

age <- c(30,32,54)

create a new dataframe from scratch

df <- data.frame(name, sex, age)

I used dplyr functions mutate and recode to change the values 1 & 2 to “Male” and “Female”.

df %>% mutate (sex= recode(sex, 1= "Male", 2= "Female"))

However, I got the following error message and wondering how I can fix this.

Error: Problem with mutate() input sex.
x unused arguments (1 = "Male", 2 = "Female")
i Input sex is recode(sex, 1= "Male",2 = "Female").
Backtrace:
9. dplyr::mutate(., sex = recode(sex, 1 = "Male", 2 = "Female"))
11. dplyr:::mutate_cols(.data, ...)

Thanks for your help

You've just about got it! The only issue is that you have to place the numbers in backticks.

library(dplyr)

name <- c("John", "Clara", "Smith")
sex <- c(1,2,1)
age <- c(30,32,54)

df <- data.frame(name, sex, age)

df %>% 
  mutate(sex = recode(sex, `1` = "Male", `2` = "Female"))
#>    name    sex age
#> 1  John   Male  30
#> 2 Clara Female  32
#> 3 Smith   Male  54

Created on 2020-09-17 by the reprex package (v0.3.0)

You need backticks because numbers may not be left of an equal sign:

library(tidyverse)
name <- c("John", "Clara", "Smith")
sex <- c(1,2,1)
age <- c(30,32,54)
df <- data.frame(name, sex, age)
df
#>    name sex age
#> 1  John   1  30
#> 2 Clara   2  32
#> 3 Smith   1  54

df %>% mutate (sex= recode(sex, 
                           `1`= "Male", 
                           `2`= "Female"))
#>    name    sex age
#> 1  John   Male  30
#> 2 Clara Female  32
#> 3 Smith   Male  54

Created on 2020-09-17 by the reprex package (v0.2.0).

1 Like

@mfherman, you were faster :smiley: !

1 Like

Thanks for your help.
I am getting the same error message. Why?

Hi @Teketo_Kassaw,

ifI do not place the backticks I get a different error than you (s.th. like unexpected '=').

Is there anything wrong with your package installation?
Could you post e.g. your sessionInfo() or your dplyr package version?

I'm using dplyr v1.0.0