[英]Compare if two dataframe objects in R are equal?
如何檢查兩個對象(例如數據幀)在 R 中的值是否相等?
通過值相等,我的意思是一個數據幀的每一列的每一行的值等於第二個數據幀中相應行和列的值。
目前尚不清楚測試兩個數據幀是否“值相等”是什么意思,但要測試值是否相同,以下是兩個值相等的不同數據幀的示例:
a <- data.frame(x = 1:10)
b <- data.frame(y = 1:10)
要測試所有值是否相等:
all(a == b) # TRUE
要測試對象是否相同(它們不是,它們具有不同的列名):
identical(a,b) # FALSE: class, colnames, rownames must all match.
此外,相同仍然有用並支持實際目標:
identical(a[, "x"], b[, "y"]) # TRUE
我們可以使用 R 包compare
來測試對象的名稱和值是否相同,只需一步。
a <- data.frame(x = 1:10)
b <- data.frame(y = 1:10)
library(compare)
compare(a, b)
#FALSE [TRUE]#objects are not identical (different names), but values are the same.
如果我們只關心值的相等性,我們可以設置ignoreNames=TRUE
compare(a, b, ignoreNames=T)
#TRUE
# dropped names
該包具有其他有趣的功能,例如compareEqual
和compareIdentical
。
這是使用arsenal
軟件包中的comparedf
的另一種方法。
它為您提供了由變量檢測到的差異、未共享的變量(例如不同的列)、未共享的觀察數以及整體比較的摘要。
df1 <- data.frame(id = paste0("person", 1:3),
a = c("a", "b", "c"),
b = c(1, 3, 4))
> df1
id a b
1 person1 a 1
2 person2 b 3
3 person3 c 4
df2 <- data.frame(id = paste0("person", 4:1),
a = c("c", "b", "a", "f"),
b = c(1, 3, 4, 4),
d = paste0("rn", 1:4))
> df2
id a b d
1 person4 c 1 rn1
2 person3 b 3 rn2
3 person2 a 4 rn3
4 person1 f 4 rn4
library(arsenal)
comparedf(df1, df2)
Compare Object
Function Call:
comparedf(x = df1, y = df2)
Shared: 3 non-by variables and 3 observations.
Not shared: 1 variables and 0 observations.
Differences found in 2/3 variables compared.
0 variables compared have non-identical attributes.
有可能得到更詳細的summary
。
summary(comparedf(df1, df2))
下面的代碼將返回幾個表:
在這里,您可以獲得有關包和功能的更多信息。
此外,您也可以使用all.equal(df1, df2)
。
[1] "Attributes: < Component “row.names”: Numeric: lengths (3, 4) differ >"
[2] "Length mismatch: comparison on first 3 components"
[3] "Component “id”: Lengths (3, 4) differ (string compare on first 3)"
[4] "Component “id”: 3 string mismatches"
[5] "Component “a”: Lengths (3, 4) differ (string compare on first 3)"
[6] "Component “a”: 2 string mismatches"
[7] "Component “b”: Numeric: lengths (3, 4) differ"
無需依賴另一個包,而是比較兩個數據集的結構(類和屬性):
structure_df1 <- sapply(df1, function(x) paste(class(x), attributes(x), collapse = ""))
structure_df2 <- sapply(df2, function(x) paste(class(x), attributes(x), collapse = ""))
all(structure_df1 == structure_df2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.