我有两个数据帧df1和df2,我相信它们具有相同的数据,但行的顺序不同。如何检查它们是否具有相同的行但可能以不同的顺序?
答案 0 :(得分:2)
我们可以先根据列
对两个数据集进行排序tmp1 <- df1[do.call(order, df1),]
row.names(tmp1) <- NULL
tmp2 <- df2[do.call(order, df2),]
row.names(tmp2) <- NULL
然后使用all.equal
检查它们是否相同
all.equal(tmp1, tmp2, check.attributes = FALSE)
注意:OP的问题是关于How can I check that they have the same rows but perhaps in a different order?
注2:没有使用外部包
答案 1 :(得分:1)
dplyr::all_equal
对此非常有用。
library(dplyr)
df_1 <- mtcars
df_2 <- mtcars %>% arrange(mpg) # Change row order
df_3 <- mtcars %>% select(disp, everything()) # change column order
all_equal(df_1, df_2, ignore_row_order = FALSE)
#> [1] "Same row values, but different order"
all_equal(df_1, df_3, ignore_col_order = FALSE)
#> [1] "Same column names, but different order"
all_equal(df_1, df_2, ignore_row_order = TRUE)
#> [1] TRUE