'How to recode within dplyr::mutate [duplicate]

I need to change my responses which are 1/2 into 1/0. Meaning correct response 1 and incorrect response 0. How can I do this using mutate or ifelse?



Solution 1:[1]

Example data - with responses in each column as either 1 or 2

(example_data <- data.frame(
  a = sample(1:2, 15, replace = TRUE),
  b = sample(1:2, 15, replace = TRUE),
  c = sample(1:2, 15, replace = TRUE),
  d = sample(1:2, 15, replace = TRUE)))

   a b c d
1  2 1 2 2
2  1 2 2 2
3  1 1 1 1
4  2 1 2 1
5  2 2 1 1
6  2 2 2 1
7  1 2 2 1
8  1 2 2 1
9  1 2 2 2
10 1 1 2 2

if we run this then column a reults change all the 2s to 0s and the 1s stay as 1s and the other columns are unaffected. I hope this is what you were trying to do?

example_data <- example_data %>% 
  mutate(a = case_when(a == 2 ~ 0,
                       a == 1 ~ 1))

   a b c d
1  0 1 2 2
2  1 2 2 2
3  1 1 1 1
4  0 1 2 1
5  0 2 1 1
6  0 2 2 1
7  1 2 2 1
8  1 2 2 1
9  1 2 2 2
10 1 1 2 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user438383