I have several factor variables with values "1" and "2" that need to be recoded to "Yes" and "No". Tidyverse mutate_at with fct_recode appear to be the right tools. However,
dataframe %>%
mutate_at(vars (var1, var9, var17) =
fct_recode(vars(var1, var9, var17),
"Yes" = "1",
"No" = "2"))
gives
Error: unexpected ')' in:
" "Yes" = "1",
"No" = "2"))"
And,
dataframe %>%
mutate_at(vars (var1, var9, var17),
funs(fct_recode(vars(var1, var9, var17),
"Yes" = "1",
"No" = "2")))
gives
Error: `f` must be a factor (or character vector).
Can someone point at my mistake or do I use mutate_at, vars or fct_recode wrong? Is there a better way in tidyverse to recode same factor levels on multiple variables, a very common task in tidying data.
The problem is your syntax in mutate_at()
.
library(dplyr)
First, I create a sample dataset:
set.seed(666)
dataframe <- data.frame(var1 = sample(c("1", "2"), 5, replace = TRUE),
var9 = sample(c("1", "2"), 5, replace = TRUE),
var17 = sample(c("1", "2"), 5, replace = TRUE))
var1 var9 var17
1 2 2 2
2 1 2 1
3 2 1 1
4 1 1 1
5 1 1 1
Then I use mutate_at()
like this: .vars
are unchanged, but .funs
is only the function, additional parameter to funs
are passed in ...
:
dataframe %>%
mutate_at(.vars = vars(var1, var9, var17),
.funs = forcats::fct_recode,
"Yes" = "1",
"No" = "2")
The end result:
var1 var9 var17
1 No No No
2 Yes No Yes
3 No Yes Yes
4 Yes Yes Yes
5 Yes Yes Yes