首页 > 解决方案 > 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

标签: rsortingselectdplyr

解决方案


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

推荐阅读