0

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

Banjo
  • 1,191
  • 1
  • 11
  • 28

1 Answers1

0

I did it this way:

f = function(x) {
  ifelse(x == 1, 1, 0)
} # Writing the function to convert 1 to 1 and all other values to 0. 


samp %>% 
  mutate_at(vars(contains("Q26")), .funs = list(t1 = ~ntile(., 2))) %>%
  # Adding "t1" to the variables (rename). 

Found it here

  mutate_at(vars(contains("t1")), funs(f))
  # Mutate the renamed variables with ifelse. 

This works, but there can be nicer solutions. Actually it´s a duplicate of the two threats.

Banjo
  • 1,191
  • 1
  • 11
  • 28