如何查找未分类的数据帧片段

让我们假设我有一个data.frame应该根据选定的列进行排序,我想确保它确实是一个案例.我可以尝试类似的东西:

library(dplyr)
mpg2 <- mpg %>% 
  arrange(manufacturer, model, year)
identical(mpg, mpg2)
[1] FALSE

但如果相同的返回FALSE,这只让我知道数据集的顺序不正确.

>如果我只想检查那些实际上顺序错误的行怎么办?如何从整个数据集中筛选出来的? (我需要避免在这里循环,因为我使用的数据集非常大)
>如果剩余的变量(不用于订购)对于制造商,型号,年份的相同值是不同的,dplyr :: arrange如何决定哪个观察首先出现?它是否保留原始数据集的订单(这里是mpg)?

最佳答案 至于第二个问题,我相信dplyr :: arrange是稳定的,它在排序列中存在关联时保留行的顺序.

通过与base :: order的结果进行比较可以看出这一点.从帮助页面,部分详细信息(我的重点):

In the case of ties in the first vector, values in the second are
used to break the ties. If the values are still tied, values in the
later arguments are used to break the tie (see the first example).
The sort used is stable (except for method = “quick”), so any
unresolved ties will be left in their original ordering.

mpg2 <- mpg %>% 
  arrange(manufacturer, model, year)

i <- with(mpg, order(manufacturer, model, year))
mpg3 <- mpg[i, ]

identical(as.data.frame(mpg2), as.data.frame(mpg3))
#[1] TRUE

除了类之外,这些值是相同的.所以dplyr :: arrange确实在关系的情况下保留了顺序.

至于第一个问题,也许下面的代码可以回答它.它只获取下一个订单号小于前一个订单号的行.这意味着这些行已经改变了相对位置.

j <- which(diff(i) < 0)
mpg[i[j], ]
点赞