r - 如何使用自定义指定的匹配标准确定每行的列之间的匹配?
问题描述
我需要识别跨列的匹配项,这些列包含数据框中每一行的相同结果的不同值标签。例如,在数据框下方的 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
解决方案
如果只有两种不同的值要比较,我们可以创建一个逻辑条件
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
推荐阅读
- android - recyclerview 上的第一项堆叠到选项卡布局
- arrays - 从数组 VBA 动态创建复选框
- javascript - React JS 中的循环或映射
- c# - .NET WebClient SSL 握手缺少用户代理和 SessionID
- windows - Windows 命令行回显日期命令
- unity3d - 在 Unity3D 中使用 Vuforia 在标记图像上播放时,最大限度地减少 AR 视频的抖动或跳跃
- android - 如何使用特定于平台的代码与 Flutter 应用共享图像?
- php - 雄辩的急切加载不适用于嵌套字段
- java - 从 Java 程序发出 HTTP 请求的最佳方式是什么?
- aws-lambda - 是否可以仅使用一个 Lambda 函数从多个 IoT 设备接收 MQTT 消息?