在R中按行判断两组列(忽略顺序)是否一致,优先dplyr方案
使用dplyr实现行内两组列的无序匹配判断
样本数据
df <- data.frame( col1 = c("a", "b", "c", "d"), col2 = c("a", "b", "d", "a"), col3 = rep("a", 4L), col4 = c("a", "b", "d", "a"), col5 = c("a", "a", "c", "d"), col6 = rep(c("b", "a"), each = 2L) )
对应表格:
| col1 | col2 | col3 | col4 | col5 | col6 |
|---|---|---|---|---|---|
| a | a | a | a | a | b |
| b | b | a | b | a | b |
| c | d | a | d | c | a |
| d | a | a | a | d | a |
需求说明
按行判断col1、col2、col3组与col4、col5、col6组的内容是否完全一致,忽略每组内列的顺序(即两组元素排序后完全相同则判定匹配)。
解决方案(基于dplyr)
核心思路是对每行的两组列分别排序后,逐元素比较是否全部相等,以下提供两种实现方式:
方法1:结合rowwise与purrr
library(dplyr) library(purrr) df_result <- df %>% rowwise() %>% mutate( group1 = list(sort(c(col1, col2, col3))), group2 = list(sort(c(col4, col5, col6))), assessment = all(group1 == group2), assessment = case_when( assessment ~ "TRUE(忽略顺序后两组内容一致)", TRUE ~ "FALSE(因两组内容不同)" ) ) %>% ungroup() %>% select(-group1, -group2)
方法2:使用apply简化(无需额外依赖purrr)
library(dplyr) df_result <- df %>% mutate( assessment = apply(., 1, function(row) { group1 <- sort(row[c("col1", "col2", "col3")]) group2 <- sort(row[c("col4", "col5", "col6")]) all(group1 == group2) }), assessment = case_when( assessment ~ "TRUE(忽略顺序后两组内容一致)", TRUE ~ "FALSE(因两组内容不同)" ) )
最终结果
运行上述代码后得到的结果如下:
| col1 | col2 | col3 | col4 | col5 | col6 | assessment |
|---|---|---|---|---|---|---|
| a | a | a | a | a | b | FALSE(因两组内容不同) |
| b | b | a | b | a | b | TRUE(忽略顺序后两组内容一致) |
| c | d | a | d | c | a | TRUE(忽略顺序后两组内容一致) |
| d | a | a | a | d | a | TRUE(忽略顺序后两组内容一致) |
内容的提问来源于stack exchange,提问作者fe108
相关产品推荐
相关产品推荐

