2012-06-11 46 views
6

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

+2

我们需要知道数据框包含什么内容:整数,数字,因子,别的东西?例如,一个非常简单的包含随机数字数据的示例数据框可以通过'df1 < - data.frame(x = rnorm(10),y = rnorm(10))'来创建,并且可以直接减去其中的两个相同的列名(但行的顺序对于正确的答案是至关重要的)。 –

回答

27

使用all.equal功能。它不排序数据帧。它将简单地检查data frame中的每个单元与另一个单元中的同一单元。 您也可以使用identical()函数。

2

没有一个例子,我不能确定我明白你想要什么。不过,我想你想要这样的东西。如果是这样,几乎可以肯定有更好的方法来做同样的事情。

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日

以下代码演示了当通过对第三个数据帧进行子集创建两个数据帧之一时,行名对identical,all.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)