r - 过滤数据集以不按列显示顶行
问题描述
这可能是一个更容易的。(首选 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 值不带关系)
解决方案
slice
函数族取代了即将被弃用的函数top_n
。指定要排序的列order_by
和n
slice_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))
推荐阅读
- c++ - cpp中包含线程的程序未完全执行
- c# - 使用下拉菜单选择
- verilog - verilog异步时钟设计问题
- html - 使用 .htaccess 在 HTML 头部插入链接和元标记
- angular - 使用数据对象 Angular 传递数据
- laravel - 缓存具有所有关系的雄辩模型,然后将其转换回具有关系的模型?
- php - PHP -S 服务?“php -S localhost index.php”图像未显示在本地主机上的服务器上
- typescript - Winston Logger 不能在剧作家测试听众/记者之外工作
- javascript - 与嵌套数组对象中的列表 ID 和子列表 ID 匹配时添加另一个属性
- reactjs - 在验证 React 表单之前阻止导航