简体   繁体   中英

use mutate_at for variables that meet two criteria dplyr R

I'm trying to reverse score (recode) some items in a dataframe. All reverse scored items end in an R, and each scale has a unique start ("hc", "out", and "hm"). I normally would just select all variables that end with an "r", but the issue is that some scales are on a 5-point scale ("hc" and "out") and others are on a 7-point scale ("hm").

Here is a sample of the much, much larger dataset:

library(tidyverse)

data <- tibble(name = c("Mike", "Ray", "Hassan"),
               hc_1 = c(1, 2, 3),
               hc_2r = c(5, 5, 4),
               out_1r = c(5, 4, 2),
               out_2 = c(2, 4, 5),
               out_3r = c(2, 2, 1),
               hm_1 = c(6, 7, 7),
               hm_2r = c(7, 1, 7))

Let's say that I want to do this one scale at a time, so I start with hm, which is on a seven-point scale.

I want to try something like this with an & statement, but I get an error:

library(tidyverse)
library(car)
data %>%
  mutate_at(vars(ends_with("r") & starts_with("hm")), ~(recode(., "1=7; 2=6; 3=5; 4=4; 5=3; 6=2; 7=1")))

Error: ends_with("r") & starts_with("hc") must evaluate to column positions or names, not a logical vector

What's a clean way to make it perform the reverse scoring on these few variables at a time? Once again, the dataset is too big too practically select individual variables at a time.

Thanks!

It would be easier to use matches here

library(tidyverse)
data %>%
     mutate_at(vars(matches("^hm.*r$")), ~(recode(.,
              "1=7; 2=6; 3=5; 4=4; 5=3; 6=2; 7=1")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM