Reputation: 1040
I have a series of variables (from a survey) with the values (1,2,5,6). I want to change the values of a specific set of variables from 5 to 3 and the 6 to 4. In this example I've only included the variables Q11_1:Q11_13 that I am interested in changing. There about 100 other variables I have not included in the example.
survey<- read_table2("Q11_1 Q11_2 Q11_3 Q11_4 Q11_5 Q11_6 Q11_7 Q11_8 Q11_9 Q11_10 Q11_11 Q11_12 Q11_13
2 5 5 2 5 5 5 5 2 5 5 2 2
1 1 1 2 2 5 5 5 1 2 2 2 1
6 5 6 6 6 6 5 6 5 6 6 6 6
6 6 6 6 6 6 6 6 6 6 6 6 6
5 6 6 6 6 6 6 6 6 6 6 6 5
6 6 6 6 6 6 6 6 5 5 6 6 5
")
I know I can use revalue to change the values like this:
survey$Q11_1 <- revalue(survey$Q11_1, c('5'='3','6'='4'))
survey$Q11_2 <- revalue(survey$Q11_2, c('5'='3','6'='4'))
survey$Q11_3 <- revalue(survey$Q11_3, c('5'='3','6'='4'))
survey$Q11_4 <- revalue(survey$Q11_4, c('5'='3','6'='4'))
survey$Q11_5 <- revalue(survey$Q11_5, c('5'='3','6'='4'))
survey$Q11_6 <- revalue(survey$Q11_6, c('5'='3','6'='4'))
survey$Q11_7 <- revalue(survey$Q11_7, c('5'='3','6'='4'))
survey$Q11_8 <- revalue(survey$Q11_8, c('5'='3','6'='4'))
survey$Q11_9 <- revalue(survey$Q11_9, c('5'='3','6'='4'))
survey$Q11_10 <- revalue(survey$Q11_10, c('5'='3','6'='4'))
survey$Q11_11 <- revalue(survey$Q11_11, c('5'='3','6'='4'))
survey$Q11_12 <- revalue(survey$Q11_12, c('5'='3','6'='4'))
survey$Q11_13 <- revalue(survey$Q11_13, c('5'='3','6'='4'))
Is there a way to apply this revaluing (or some other function) in a more efficient way? My solution seems unnecessarily chunky. Any help appreciated. I was hoping for a pipe/dplyr solution.
Thank you!!!
Upvotes: 0
Views: 50
Reputation: 4151
Here is a solution matching the column name "Q11"
library(tidyverse)
survey<- read_table2("Q11_1 Q11_2 Q11_3 Q11_4 Q11_5 Q11_6 Q11_7 Q11_8 Q11_9 Q11_10 Q11_11 Q11_12 Q11_13
2 5 5 2 5 5 5 5 2 5 5 2 2
1 1 1 2 2 5 5 5 1 2 2 2 1
6 5 6 6 6 6 5 6 5 6 6 6 6
6 6 6 6 6 6 6 6 6 6 6 6 6
5 6 6 6 6 6 6 6 6 6 6 6 5
6 6 6 6 6 6 6 6 5 5 6 6 5
")
survey %>%
mutate(across(contains("Q11"),.fns = ~ case_when(.x == 5 ~ 3,
.x == 6 ~ 4,
TRUE ~ .x)))
#> # A tibble: 6 x 13
#> Q11_1 Q11_2 Q11_3 Q11_4 Q11_5 Q11_6 Q11_7 Q11_8 Q11_9 Q11_10 Q11_11 Q11_12
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2 3 3 2 3 3 3 3 2 3 3 2
#> 2 1 1 1 2 2 3 3 3 1 2 2 2
#> 3 4 3 4 4 4 4 3 4 3 4 4 4
#> 4 4 4 4 4 4 4 4 4 4 4 4 4
#> 5 3 4 4 4 4 4 4 4 4 4 4 4
#> 6 4 4 4 4 4 4 4 4 3 3 4 4
#> # ... with 1 more variable: Q11_13 <dbl>
Created on 2020-06-18 by the reprex package (v0.3.0)
Upvotes: 1