0

I have a data frame with 2 variables:

Correct FACE.RESP
1       1         1
2       2         1
3       1         2
4       2         2
5       2         2
6       2         1

I would like to recode/replace the values in the 'FACE.RESP' column under a condition that if the value in 'FACE.RESP' matches the value in 'Correct', the value in 'FACE.RESP' should be rewritten to 1. If the value in 'FACE.RESP' doesn't match the value in 'Correct', the value in 'FACE.RESP' should be recoded to 0.

I tried the following code using mutate and case_when:

mutate(FACE.RESP = case_when(FACE.RESP == Correct ~ '1', FACE.RESP <= Correct ~ '0', FACE.RESP >= Correct ~ '1'))

but the results is this:

Correct FACE.RESP
5        2         2
6        2         1
7        1        NA
8        2        NA
9        2        NA
10       1        NA

Could anyone suggest how to achieve the required outcome and explain what is wrong with the above line of code?

3 Answers 3

2

You need to check only for one condition that FACE.RESP and Correct values are the same and assign all other values to 0.

library(dplyr)
df %>% mutate(FACE.RESP = case_when(FACE.RESP == Correct ~ 1,TRUE ~ 0))

#  Correct FACE.RESP
#1       1         1
#2       2         0
#3       1         0
#4       2         1
#5       2         1
#6       2         0

However, a simpler approach is to compare the two columns and convert the logical values to integer values using + at the beginning.

df$FACE.RESP <- +(df$Correct == df$FACE.RESP)

data

df <- structure(list(Correct = c(1L, 2L, 1L, 2L, 2L, 2L), FACE.RESP = c(1L, 
1L, 2L, 2L, 2L, 1L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))
Sign up to request clarification or add additional context in comments.

Comments

2

We can use as.integer

df$FACE.RESP <- as.integer(df$Correct == df$FACE.RESP)

data

df <- structure(list(Correct = c(1L, 2L, 1L, 2L, 2L, 2L), FACE.RESP = c(1L, 
1L, 2L, 2L, 2L, 1L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

Comments

1

Here is another dplyr solution.

library(dplyr)

df %>% mutate(FACE.RESP = +(Correct == FACE.RESP))
#  Correct FACE.RESP
#1       1         1
#2       2         0
#3       1         0
#4       2         1
#5       2         1
#6       2         0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.