r - dplyr:在不同列上选择 n 行列的有效方法
问题描述
有没有更好的方法来做到这一点?尤其是选择 10 行列hp
而不像这样分别使用两个函数。我检查了使用top_n(10)
,但使用后它不起作用arrange()
。
mtcars %>% arrange(desc(.[[3]])) %>% select(hp) %>% head(10)
# hp
#1 205
#2 215
#3 230
#4 175
#5 175
#6 245
#7 264
#8 245
#9 150
#10 150
解决方案
a <-
mtcars %>%
top_n(10, disp) %>%
arrange(desc(disp)) %>%
select(hp)
b <- mtcars %>% arrange(desc(.[[3]])) %>% select(hp) %>% head(10)
identical(a, b)
#[1] TRUE
您也可以先安排,但会慢一些
a <-
mtcars %>%
arrange(desc(disp)) %>%
top_n(10, disp) %>% # same as head(10) since already sorted
select(hp)
b <- mtcars %>% arrange(desc(.[[3]])) %>% select(hp) %>% head(10)
identical(a, b)
#[1] TRUE
推荐阅读
- reactjs - ReactJS socket.io 在 socket 下定义或调用的任何函数都会给出类型错误而不是函数
- web-component - 预渲染使用 StencilJS Web 组件构建的网站页面
- ios - ViewController - 全屏
- php - 查询上个月的假期/病假
- typescript - 我如何 Object.assign 给 Typescript 中对象的子属性?
- java - 如果失败,如何重新启动线程
- python - 如何从模型本身发现火炬模型名称?
- c - 将 C 回调(无上下文)包装到 Swift 闭包中
- ruby-on-rails - 在 rails 中替代 group_by
- demandware - 为 Salesforce 商务云市场构建应用程序