首页 > 解决方案 > 过滤数据集以不按列显示顶行

问题描述

这可能是一个更容易的。(首选 tidyverse 解决方案)

两个问题 Q1. 为什么下面没有按最大 Sepal.Length 值给我前 4 行

library(tidyverse)
1. iris %>% top_n(Sepal.Length,4)

Q2我想做与top_n相反的slice_max。我想显示数据框中没有前 n 行的数据框

library(tidyverse)
#something like below
iris %>% filter(!top_n(Sepal.Length,4))

1. 的输出应该是 4 行,2. 的输出应该是 146 行(150-4 行由顶部 Sepal.Length 值不带关系)

标签: rdplyrtidyverse

解决方案


slice函数族取代了即将被弃用的函数top_n。指定要排序的列order_bynslice_max

library(dplyr)
iris %>% 
      slice_max(order_by = Sepal.Length, n = 4)

默认情况下,它使用with_ties = TRUE. 如果我们需要删除关系,请将其指定为FALSE


对于第二种情况,setdiff(里面有data.frame方法dplyr)可以使用

iris %>% 
  slice_max(order_by = Sepal.Length, n = 4) %>% 
  setdiff(iris, .)

或者另一种选择是根据排名创建dense_rank排名filter

iris %>%
     filter(!dense_rank(-Sepal.Length) %in% 1:4) 

如果我们只想删除 4 行,则使用row_number

iris %>%
    filter(!row_number(-Sepal.Length) %in% 1:4)

或与slice

iris %>% 
    slice(setdiff(row_number(-Sepal.Length), 1:4))

推荐阅读