0

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?

Phil
  • 7,287
  • 3
  • 36
  • 66
  • `mutate(df, newvar = if_else(old_var == 2, 0, old_var))` – Phil Feb 23 '22 at 15:08
  • Since you're converting to essentially a boolean, if your variable is `x`, you can do `+(x == 1)` to test whether the value is equal to 1, then convert the boolean to numeric – camille Feb 23 '22 at 15:48

1 Answers1

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
user438383
  • 5,716
  • 8
  • 28
  • 43