我有两个数据框,每个有两列(例如,x和y)。我需要比较两个数据框,并查看x或y中的任何值或x和y中的任何值在两个数据框中是否相似。如何比较两个数据框?
6
A
回答
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.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)
相关问题
- 1. 两个数据框的比较
- 2. 如何比较两个波形数据?
- 3. 如何比较两个数据库?
- 4. PySpark:如何比较两个数据帧
- 5. 如何比较两个音频数据?
- 6. 如何比较两个表格数据?
- 7. 比较两个数据库
- 8. 比较两个数据集
- 9. 比较两个数据行
- 10. 比较两个数据表
- 11. 如何比较熊猫中两个数据框的值?
- 12. 如何比较两个文本框?
- 13. 如何比较两个访问数据库以比较数据库记录
- 14. 比较两个文本框
- 15. 比较两个不同数据框的两列
- 16. 如何比较来自两个不同数据库的数据?
- 17. 如何比较两个System.Types?
- 18. 如何比较两个DateTimeOffSet?
- 19. 如何比较两个表
- 20. 如何比较两个arraycollection
- 21. 如何比较两个.exes
- 22. 如何比较两个NSMutableArrays?
- 23. 如何比较两个LTL?
- 24. 如何比较两个HashSet?
- 25. 如何比较两个RippleDrawables?
- 26. 如何比较两个NSMutableArray?
- 27. 如何比较两个ID
- 28. 如何比较两个ArrayList
- 29. 如何比较两个NSIndexPaths?
- 30. 如何比较两个ImageViews?
我们需要知道数据框包含什么内容:整数,数字,因子,别的东西?例如,一个非常简单的包含随机数字数据的示例数据框可以通过'df1 < - data.frame(x = rnorm(10),y = rnorm(10))'来创建,并且可以直接减去其中的两个相同的列名(但行的顺序对于正确的答案是至关重要的)。 –