我想比较两个数据帧并检查是否有重复的行。 我们假设列的顺序无关紧要,如果df1看起来像那样:
V2 V3
71 78
90 13
12 67
56 32
和df2是这样的:
V2 V3
89 45
77 88
78 71
90 13
然后来自两个df的非重复行将是:
12 67
56 32
89 45
77 88
如何以简单的方式实现这一目标?
答案 0 :(得分:3)
你可以尝试
df3 <- rbind(df1, df2)
df4 <- df3
df3[] <- cbind(do.call(pmax, df3), do.call(pmin, df3))
df4[!(duplicated(df3)|duplicated(df3, fromLast=TRUE)),]
# V2 V3
#3 12 67
#4 56 32
#5 89 45
#6 77 88
答案 1 :(得分:1)
下面提供的解决方案适用于您的示例数据。对于相当大的数据集,这种方法可能效率低下。再说一次,计算机时间便宜。 :)
df1 <- read.table(text = " V2 V3
71 78
90 13
12 67
56 32", header = TRUE)
df2 <- read.table(text = "V2 V3
89 45
77 88
78 71
90 13", header = TRUE)
throwoutFunction <- function(x, ca) {
find.duplicates <- apply(ca, MARGIN = 1, FUN = function(y, x) y %in% x, x = x)
filter.duplicates <- apply(find.duplicates, MARGIN = 2, all)
if (any(filter.duplicates)) {
return(data.frame(V2 = NA, V3 = NA))
} else {
data.frame(V2 = x[1], V3 = x[2])
}
}
out1 <- do.call("rbind", apply(df1, MARGIN = 1, FUN = throwoutFunction, ca = df2))
out2 <- do.call("rbind", apply(df2, MARGIN = 1, FUN = throwoutFunction, ca = df1))
out <- na.omit(rbind(out1, out2))
rownames(out) <- 1:nrow(out)
out
V2 V3
1 12 67
2 56 32
3 89 45
4 77 88