我有两个数据帧,每个数据帧有两列(例如,x和y).我需要比较两个数据帧,看看两个数据帧中x或y中的任何值或者x和y中的任何值是否相似.
没有一个例子,我不能确定我了解您想要什么。但是,我认为您想要这样的东西。如果是这样,几乎肯定会有更好的方法来做同样的事情。
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日
下面的代码演示了行名称可能对产生的影响identical
,all.equal
以及which
通过子集第三个数据帧创建两个数据帧之一时的效果。如果要比较的两个数据帧之间的行名不同,则identical
也all.equal
不会返回TRUE
。但是,which
仍然可以用来比较列x
和y
两个数据帧之间的数据。如果行的名称设置为NULL
用于两个数据帧进行比较,然后都identical
和all.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)