mercredi 17 mars 2021

How to recode multiple choice answers in R using dplyr?

I have a dataset with answers to a large number of multiple choice questions. I now want to recode these answers in either true (1) or false (0). I

`#ID  q1 q2 q3 cq1 cq2 cq3
 #1   1  2  1  NA  NA  NA
 #2   1  2  2  NA  NA  NA
 #3   2  2  2  NA  NA  NA
 #4   1  2  1  NA  NA  NA`

what I want is this:

`#ID  q1 q2 q3 cq1 cq2 cq3
 #1   1  2  1  0  0  0
 #2   1  2  2  0  0  1
 #3   2  2  2  1  0  1
 #4   1  2  1  0  0  0`

I know that I could write out all answers like this:

`data_re <- data %>% 
  mutate(cq1 = if_else(q1==2, 1, 0),
         cq2 = if_else(q2==1, 1, 0),
         cq3 = if_else(q3==2, 1, 0))`

But is there any way how to automatically do this (similar to this approach: How to mutate_at multiple columns on a condition on each value?

However, I would have to generate the variablename of the conditional variable automatically. I tried this:

`names_answer_two_correct <- c("q1", "q3")
 cnames_answer_two_correct <- paste0("c", names_answer_two_correct)

 for (i in 1:length(names_answer_two_correct)) {
   data_re <- data %>%
   mutate(names_answer_two_correct[i] = if_else(cnames_answer_two_correct[i]== 2, 1, 0))
}`

But I get "Error: unexpected '=' in:" Does anyone know a solution?

Aucun commentaire:

Enregistrer un commentaire