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

相关内容

最新更新