使用dplyr的多个group_by和top_n

时间:2019-01-14 03:05:48

标签: r dplyr

我有一个数据框,我正在尝试过滤和删除一些数据。那个df看起来像这样:

Event    Name    Team    Rank
1        Mike    B       1
1        Joe     A       2
1        Tom     C       3
1        Bill    B       4
2        Joe     A       1
2        Tom     C       2
...

我正在尝试过滤数据,所以我每人只有3个事件(按他们的最佳排名),每个团队只有18个事件。

我每人能够使用以下方法获得3个事件:

df <- df %>% 
group_by(Name) %>%
top_n(-3,Rank)

但每队18个人使我绊倒。我需要group_by团队和姓名吗?如果是这样,怎么办?我尝试过的所有方法都无效。

此外,我宁愿没有联系,但现在还很小。

编辑:这是一个大df,但结构如下:

structure(list(event = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 6L, 
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), name = structure(c(22L, 
16L, 28L, 27L, 17L, 21L, 3L, 2L, 8L, 13L, 15L, 28L, 5L, 16L, 
17L, 2L, 22L, 3L, 10L, 21L, 5L, 15L, 24L, 29L, 1L, 2L, 18L, 25L, 
7L, 21L, 29L, 19L, 25L, 18L, 9L, 23L, 14L, 4L, 29L, 6L, 29L, 
19L, 9L, 26L, 25L, 14L, 4L, 11L, 20L, 12L), .Label = c("Andreas", 
"Andrej", "Blaise", "Brendan", "Coleman", "Colton", "Cooper", 
"Corben", "Eric", "Giovanni", "Graham", "Hayden", "Ian", "Jack", 
"Jacob", "Justin", "Kanoa", "Lane", "Marcelo", "Matthew", "Miles", 
"Nyls", "Robby", "Rodrigo", "Sadler", "T.C.", "Thomas", "Will", 
"Zach"), class = "factor"), team = structure(c(1L, 1L, 2L, 3L, 
2L, 4L, 5L, 6L, 7L, 3L, 1L, 2L, 1L, 1L, 2L, 6L, 1L, 5L, 1L, 4L, 
1L, 1L, 7L, 9L, 1L, 6L, 3L, 9L, 8L, 4L, 9L, 6L, 9L, 3L, 1L, 8L, 
1L, 8L, 6L, 7L, 9L, 6L, 1L, 6L, 9L, 1L, 8L, 6L, 8L, 6L), .Label = c("A", 
"B", "C", "D", "E", "F", "G", "H", "J"), class = "factor"), rank = c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 
7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 
7L, 8L, 9L, 10L)), class = "data.frame", row.names = c(NA, -50L
))

2 个答案:

答案 0 :(得分:1)

类似的事情应该起作用

df %>% 
group_by(name, team) %>%
filter(row_number() <= 18)

@NelsonGon建议立即将两者分组,这似乎可以更简洁地给出确切结果。

答案 1 :(得分:0)

这吗?

 library(tidyverse)
    df %>% 
      arrange(team,desc(rank)) %>% 
      group_by(event,team) %>% 
      top_n(3,rank)

当前输出:

   event name     team   rank
   <int> <fct>    <fct> <int>
 1     2 Giovanni A         9
 2     2 Nyls     A         7
 3     4 Jack     A         7
 4     6 Jack     A         6
 5     3 Andreas  A         5
 6     4 Eric     A         5
 7     2 Justin   A         4
 8     6 Eric     A         3
 9     1 Justin   A         2
10     3 Jacob    A         2

测试:

df %>% 
  arrange(team,desc(rank)) %>% 
  group_by(name,team) %>% 
  top_n(3,rank) %>% 
  filter(name=="Justin")
  event name   team   rank
  <int> <fct>  <fct> <int>
1     2 Justin A         4
2     1 Justin A         2