1

I'm trying to recode values in multiple columns, which with the same coding scheme. I use code mutate_at from this post but did not work.

My data frame is like this, and I want to recode "Neutral = 3" and "Agree = 4"

A              B            C
Neutral       Agree        Neutral
Neutral       Agree        Agree
Agree         Neutral      Neutral

My code

df %>%
  mutate_at(c("A", "B", "C"), funs(as.character)) %>%
  mutate_at(c("A", "B", "C"), funs(recode(.,"Neutral"=3, "Agree"=4)))

Error shows

Error in recode(A, Neutral = 3, Agree = 4) : 
  unused arguments (Neutral = 3, Agree = 4)

Thanks!

Lumos
  • 1,303
  • 2
  • 17
  • 32

1 Answers1

0

You can use :

library(dplyr)
df %>% mutate_all(~recode(., "Neutral"=3, "Agree"=4))
#If there are other columns
#df %>%  mutate_at(vars(A:C), ~recode(., "Neutral"=3, "Agree"=4))

#  A B C
#1 3 4 3
#2 3 4 4
#3 4 3 3

We can also use ifelse/case_when if there are limited values that can be taken.

df %>%  mutate_all(~ifelse(.  == "Neutral", 3, 4))

Or in base R using lapply.

df[] <- lapply(df, function(x) ifelse(x == "Neutral", 3, 4))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213