如何比较两个数据帧?

时间:2012-06-11 11:05:05

标签: r dataframe

我有两个数据帧,每个数据帧有两列(例如,x和y)。我需要比较两个数据帧,看看x或y中的任何值或x和y中的任何值在两个数据帧中是否相似。

2 个答案:

答案 0 :(得分:31)

使用all.equal功能。它不对数据帧进行排序。它只会检查data frame中的每个单元格与另一个单元格中的相同单元格。 您也可以使用identical()功能。

答案 1 :(得分:4)

如果没有例子,我无法确定我理解你想要什么。但是,我想你想要这样的东西。如果是这样,几乎肯定有更好的方法来做同样的事情。

a <- matrix(c(1,2,
              3,4,
              5,6,
              7,8), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

b <- matrix(c(1,2,
              9,4,
              9,6,
              7,9), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

cc <- matrix(c(NA,NA,
              NA,NA,
              NA,NA,
              NA,NA), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

for(i in 1:dim(a)[1]) {
for(j in 1:dim(a)[2]) {
if(a[i,j]==b[i,j]) cc[i,j]=a[i,j]
}
}

cc

编辑:2013年1月8日

以下行将告诉您两个矩阵中哪些单元格不同:

which(a != b, arr.ind=TRUE)

#      row col
# [1,]   2   1
# [2,]   3   1
# [3,]   4   2

如果两个矩阵a和b相同,那么:

which(a != b)

# integer(0)

which(a != b, arr.ind=TRUE)

# row col

编辑2012年1月9日

以下代码演示了当通过对第三个数据帧进行子集化创建两个数据帧之一时,行名称可能对identicalall.equalwhich产生的影响。如果要比较的两个数据帧之间的行名称不同,则identicalall.equal都不会返回TRUE。但是,which仍可用于比较两个数据框之间的列xy。如果对于要比较的两个数据框中的每一个,行名称都设置为NULL,则identicalall.equal都将返回TRUE

df1 <- read.table(text = "
     group  x  y 
       1   10 20
       1   10 20
       1   10 20
       1   10 20
       2    1  2
       2    3  4
       2    5  6
       2    7  8
", sep = "", header = TRUE)

df2 <- read.table(text = "
     group  x  y 
       2    1  2
       2    3  4
       2    5  6
       2    7  8
", sep = "", header = TRUE)

# df3 is a subset of df1

df3 <- df1[df1$group==2,]

# rownames differ between df2 and df3 and
# therefore neither 'all.equal' nor 'identical' return TRUE
# even though the i,j cells of df2 and df3 are the same.
# Note that 'which' indicates no i,j cells differ between df2 and df3 

df2
df3

all.equal(df2, df3)
identical(df2, df3)
which(df2 != df3)

# set row names to NULL in both data sets and
# now both 'all.equal' and 'identical' return TRUE.
# Note that 'which' still indicates no i,j cells differ between df2 and df3

rownames(df2) <- NULL
rownames(df3) <- NULL

df2
df3

all.equal(df2, df3)
identical(df2, df3)
which(df2 != df3)