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!

1
  • BTW: Except for a warning ... your code works fine on my machine using dplyr 0.8.5 Commented Mar 27, 2020 at 8:47

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.