如何准确提取三个最大计数的观察值

How to extract exactly three observations with biggest count

如何仅提取三个关于某个变量的最佳观察值,例如。计数(下面示例数据中的n var)?我想避免排列行,所以我想我可以使用 dplyr::min_rank.

ex <- structure(list(code = c("17.1", "6.2", "151.5", "78.1", "88.1", 
"95.1", "45.2", "252.2"), id = c(1, 2, 3, 4, 5, 6, 7, 8), n = c(6L, 
5L, 8L, 10L, 6L, 3L, 4L, 6L)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -8L))

ex %>% 
  filter(min_rank(desc(n)) <= 3)

但如果有关系,它可以给出 3 个以上的观察结果。例如上面的命令 returns 五行:

# A tibble: 5 x 3
  code     id     n
  <chr> <dbl> <int>
1 17.1      1     6
2 151.5     3     8
3 78.1      4    10
4 88.1      5     6
5 252.2     8     6

我怎样才能准确提取 3 个观察值? (无论在平局的情况下返回哪个观察值)

我们可以使用 row_number 可以将列作为参数

ex %>% 
  filter(row_number(desc(n)) <= 3)
# A tibble: 3 x 3
#   code     id     n
#   <chr> <dbl> <int>
#1 17.1      1     6
#2 151.5     3     8
#3 78.1      4    10

在基础 R 中,我们可以使用

ex[tail(order(ex$n),3), ]