I have some variables which I want to convert in the same way.
library(dplyr)
glimpse(samp)
Observations: 5
Variables: 4
$ Q26_1_1 <dbl+lbl> 1, 3, NA, 2, 4
$ Q26_2_1 <dbl+lbl> 1, 3, NA, 2, 4
$ Q26_3_1 <dbl+lbl> 1, 3, NA, 2, 4
$ Q26_4_1 <dbl+lbl> 1, 3, NA, 2, 4
The range of all variables is 1 to 5. If an entry is 1 I want to convert it into 1 else to 0.
Normally I use ifelse
like:
samp %>%
mutate(Q26_1_1_t1 = ifelse(Q26_1_1 == 1, 1, 0),
Q26_2_1_t1 = ifelse(Q26_2_1 == 1, 1, 0),
Q26_3_1_t1 = if_else(Q26_3_1 == 1, 1, 0),
Q26_4_1_t1 = ifelse(Q26_4_1 == 1, 1, 0))
However, If there are 40 or 60 variables its quite time-consuming. Is there another way like mutate_at
to make a shorter code?
Here is an example. I adapt it this way:
f = function(x) {
ifelse(x == 1, 1, 0)
}
samp %>%
mutate_at(vars(contains("Q26")), funs(f))
...but the renaming is not included (e.g. Q26_4_1 to Q26_4_1_t1).
Adding a suffix and changing values of multiple variables