我有兩個數據框,每個有兩列(例如,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))'來創建,並且可以直接減去其中的兩個相同的列名(但行的順序對於正確的答案是至關重要的)。 –