0

I have a dataframe of survey responses on a scale 1-5. I want to recode them so that 1-3 is a 0, and 4-5 is a 1, preferably without just using a for loop. I understand that I should be able to use mutate_all, but I can't figure out how to build the .funs to make that work. Would lapply/sapply work instead?

Based on my understanding of mutate_all, I tried this

A03 <- A02 %>% mutate_all(if(%in%c(4,5){1}))

and got this error:

Error: unexpected SPECIAL in "A03 <- A02 %>% mutate_all(if(%in%"

Any insight would be very valuable.

ETA:

I managed to cobble together a working answer using

recode_response <- function(r){
  if(r %in% c(4,5)){
    1
  } else(0)
}
A03 <- A02 %>% apply(c(1,2),recode_response) 

but

A03 <- A02 %>% mutate(across(everything(), ~ifelse(.x <= 3, 0, 1)))

is a slicker answer.

Kieren Duffy
  • 123
  • 4
  • 3
    Perhaps `A03 <- A02 %>% mutate(across(everything(), ~ifelse(.x <= 3, 0, 1)))`? It's hard to say without a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) complete with example input and expected output. – jared_mamrot Aug 17 '23 at 09:33
  • @jared_mamrot That's perfect, thank you! – Kieren Duffy Aug 17 '23 at 09:39

0 Answers0