首页 > 解决方案 > R比较两个数据集中每一行的重复值

问题描述

我想比较每一行的值是否相同。在这种情况下,duplicated 和 all_equal 函数不适用。

可重现的样本数据

df1 <- data.frame(a=c(1,2,3),b=c(4,5,6))
df2 <- data.frame(a=c(1,2,4),b=c(4,5,6))

> df1
  a b
1 1 4
2 2 5
3 3 6
> df2
  a b
1 1 4
2 2 5
3 4 6

预期产出

final <- data.frame(a=c(1,2,4),b=c(4,5,6),c=c('T','T','F'))
#c column is the result I need. whether the values ​​in each row are the same.

>final
  a b c
1 1 4 T
2 2 5 T
3 4 6 F

我尝试下面的方法......但这很复杂。

#1. making idx of df1, df2
#2. and full_join
#3. and left_join df1
#4. and left_join df2
df1$idx1 <- 1:nrow(df1)
df2$idx2 <- 1:nrow(df2)

df3<-full_join(df1,df2,by=c('a','b'))
df3<-left_join(df3,df1,by=c('a','b'))
df3<-left_join(df3,df2,by=c('a','b'))  #This may or may not work..

我认为必须有更好的方法。帮助!

标签: r

解决方案


您可以通过以下方式获取“c”列:

c <- df1$a == df2$a & df1$b == df2$b

给出 TRUE TRUE FALSE。看起来你想把它绑定到 df2,所以

cbind.data.frame(df2, c)

推荐阅读