Im trying to write a code, that will take colnames out of a given vector, and in each of these columns recode 1<-5,2<-4,3<-3,4<-2,5<-1 big5qflip is the vectore of columns that I need to recode out of a questionnaire, I'm having trouble getting it to work, and writing case_when correctly
big5new%>%mutate_at(vars(big5qflip),case_when(
big5qflip==1~5,
big5qflip==2~4,
big5qflip==3~3,
big5qflip==4~2,
big5qflip==5~2
))
thank you!
when I tried the code above I got the follwing error
Error in mutate_at()
:
! .funs
must be a one sided formula, a function, or a function name.
Run rlang::last_error()
to see where the error occurred.
CodePudding user response:
mutate_at
has been superseded by across
, so here's a solution using this function. Also notice the {{ ... }}
to refer to the colnames in big5qflip
:
library(dplyr)
big5new <- data.frame(
X = c(1, 2, 1, 3, 2),
Y = c(4, 4, 4, 4, 4),
Z = c(1, 1, 1, 1, 1)
)
big5qflip <- c("X", "Y")
newcodes <- 5:1
names(newcodes) <- 1:5
big5new %>%
mutate(
across(
{{ big5qflip }},
~ do.call(recode, append(list(.x =.x), newcodes))
)
)
CodePudding user response:
Here is another option. You can use factor
to set the levels in the reverse order and then as.numeric
to get the level index which is the inverse of the number.
library(tidyverse)
big5new <- data.frame(
X = c(1, 2, 1, 3, 2),
Y = c(4, 4, 4, 4, 4),
Z = c(1, 1, 1, 1, 1)
)
big5qflip <- c("X", "Y")
big5new |>
mutate(across(all_of(big5qflip), \(x) as.numeric(factor(x, levels = 5:1))))
#> X Y Z
#> 1 5 2 1
#> 2 4 2 1
#> 3 5 2 1
#> 4 3 2 1
#> 5 4 2 1