2012-06-11 73 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)