首页 > 解决方案 > 如何使用自定义指定的匹配标准确定每行的列之间的匹配?

问题描述

我需要识别跨列的匹配项,这些列包含数据框中每一行的相同结果的不同值标签。例如,在数据框下方的 A 列中,使用了术语“是”和“否” - 但是 - 在 B 列中,使用了术语“肯定”和“否定”。当 A 列值为“是”且 B 列值为“肯定”时 - 或 - 当 A 列值为“否”且 B 列值为“负”时,我需要找到一种表示“匹配”的方法. 当这些情况没有发生时,我还需要指出“失败”。

换句话说,我正在寻找可以在下面示例数据的“match_result”列中产生结果的代码:

id <- seq(1, 10)
A <- c(rep("yes", 3), rep("no", 3), rep("yes", 3), "no")
B <- c(rep("affirmative", 5), rep("negative", 5))
match_result <- c(rep("match", 3), rep("fail", 2), "match", rep("fail", 
3), "match")

dat <- data.frame(id, A, B, match_result)
dat

 id   A           B                  match_result
 1    yes         affirmative        match
 2    yes         affirmative        match
 3    yes         affirmative        match
 4    no          affirmative        fail
 5    no          affirmative        fail
 6    no          negative           match
 7    yes         negative           fail
 8    yes         negative           fail
 9    yes         negative           fail
10    no          negative           match

标签: rmatch

解决方案


如果只有两种不同的值要比较,我们可以创建一个逻辑条件

dat$match_result1 <- c("fail", "match")[with(dat, 
         A == "yes" & B == "affirmative" | A == "no" & B == "negative") + 1]

dat
#   id   A           B match_result match_result1
#1   1 yes affirmative        match         match
#2   2 yes affirmative        match         match
#3   3 yes affirmative        match         match
#4   4  no affirmative         fail          fail
#5   5  no affirmative         fail          fail
#6   6  no    negative        match         match
#7   7 yes    negative         fail          fail
#8   8 yes    negative         fail          fail
#9   9 yes    negative         fail          fail
#10 10  no    negative        match         match

推荐阅读