简体   繁体   中英

Compare Columns and replace Values in R

I'm trying to compare different columns ("Test1" - "Test3") to one basic-column ("Criteria") and replace values depending on the result of the comparison.

Here is an example - Consider the following data:

Test.data <- data.frame(c("Yes", "Yes", "No", "Yes"))
Test.data$Test1 <- (c("No", "No", "Yes", "Yes"))
Test.data$Test2 <- (c("Yes", "No", "Yes", "No"))
Test.data$Test3 <- (c("Yes", "Yes", "Yes", "Yes"))
colnames(Test.data) <- c("Criteria", "Test1", "Test2", "Test3")


  Criteria Test1 Test2 Test3
1      Yes    No   Yes   Yes
2      Yes    No    No   Yes
3       No   Yes   Yes   Yes
4      Yes   Yes    No   Yes

Is there an efficient way to replace the values in "Test1" - "Test3" with 0, if the value in the specific column corresponds to the basic-column and with 1, if it does not? Maybe with an if-function?

A result should look like this:

  Criteria Test1 Test2 Test3
1      Yes    1      0     0
2      Yes    1      1     0
3       No    1      1     1
4      Yes    0      1     0

Thanks everyone for taking time! You guys are doing a great job!

You can use:

Test.data[-1] <- +(Test.data$Criteria != Test.data[-1])
Test.data

#  Criteria Test1 Test2 Test3
#1      Yes     1     0     0
#2      Yes     1     1     0
#3       No     1     1     1
#4      Yes     0     1     0

[-1] is to ignore the Criteria column as we don't want to change it. We compare all the columns with Criteria column and assign 1 if they are different and 0 otherwise. + is used to change logical values ( TRUE / FALSE ) to integer values ( 1 / 0 ).

A dplyr approach:

library(dplyr)

Test.data %>% mutate(across(-Criteria, ~as.numeric(. != Criteria)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM