如何比较两个数据帧?

sat*_*hya 7 r dataframe

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

Max*_*x C 30

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


Mar*_*ler 5

没有一个例子,我不能确定我了解您想要什么。但是,我认为您想要这样的东西。如果是这样,几乎肯定会有更好的方法来做同样的事情。

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
Run Code Online (Sandbox Code Playgroud)

编辑:2013年1月8日

下面的行将告诉您两个矩阵之间的哪些单元格不同:

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

#      row col
# [1,]   2   1
# [2,]   3   1
# [3,]   4   2
Run Code Online (Sandbox Code Playgroud)

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

which(a != b)

# integer(0)

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

# row col
Run Code Online (Sandbox Code Playgroud)

EDIT 2012年1月9日

下面的代码演示了行名称可能对产生的影响identicalall.equal以及which通过子集第三个数据帧创建两个数据帧之一时的效果。如果要比较的两个数据帧之间的行名不同,则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)
Run Code Online (Sandbox Code Playgroud)