根据groupby过滤天数

时间:2018-05-29 13:55:07

标签: r filter

我有一个df,我想基于分组筛选出一列。我希望按组合保持分组({ccoddtree1tree2),如果天> 4,然后保留,否则放弃

df <- data_frame(
cc = c('BB', 'BB', 'BB', 'BB','BB', 'BB','BB', 'BB', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 
     'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ'),
odd = c(3434, 3434, 3434, 3434, 3435, 3435, 3435, 3435, 3434, 3434, 3434, 3434, 3435, 3435, 3435, 3435, 3434, 3434, 3434, 3434, 3435, 3435, 3435, 3435),
tree1 = c('ASP', 'ASP', 'ASP', 'ASP', 'SAP', 'SAP', 'SAP', 'SAP', 'ASP', 'ASP', 'ASP', 'ASP', 'SAP', 'SAP', 'SAP', 'SAP', 'ASP', 'ASP', 'ASP', 'ASP', 'SAP', 'SAP', 'SAP', 'SAP'),
tree2 = c('ATK', 'ATK','ATK','ATK','ATK','ATK','ATK','ATK', 'ATK', 'ATK','ATK','ATK','ATK','ATK','ATK','ATK', 'ATK', 'ATK','ATK','ATK','ATK','ATK','ATK','ATK'),
day = c(1, 2, 3, 4, 3, 4, 5, 6, 2, 3, 4, 5, 1, 3, 5, 7, 1, 2, 6, 8, 2, 4, 6, 8)
)

我尝试了这个但是这会丢弃day小于4的任何行

df1 <- df %>%
  arrange(cc, odd, tree1, tree2, day) %>% 
  group_by(cc, odd, tree1, tree2) %>% 
  filter(day > 4)

我想得到如下的df。

df2 <- data_frame(
  cc = c('BB', 'BB','BB', 'BB', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 'DD', 
     'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ', 'ZZ'),
  odd = c(3435, 3435, 3435, 3435, 3434, 3434, 3434, 3434, 3435, 3435, 3435, 3435, 3434, 3434, 3434, 3434, 3435, 3435, 3435, 3435),
  tree1 = c('SAP', 'SAP', 'SAP', 'SAP', 'ASP', 'ASP', 'ASP', 'ASP', 'SAP', 'SAP', 'SAP', 'SAP', 'ASP', 'ASP', 'ASP', 'ASP', 'SAP', 'SAP', 'SAP', 'SAP'),
  tree2 = c('ATK','ATK','ATK','ATK', 'ATK', 'ATK','ATK','ATK','ATK','ATK','ATK','ATK', 'ATK', 'ATK','ATK','ATK','ATK','ATK','ATK','ATK'),
  day = c(3, 4, 5, 6, 2, 3, 4, 5, 1, 3, 5, 7, 1, 2, 6, 8, 2, 4, 6, 8)
)

1 个答案:

答案 0 :(得分:1)

你可以尝试

df %>%
  group_by(cc, odd, tree1, tree2) %>% 
  filter(any(day > 4)) 
# A tibble: 20 x 5
   cc      odd tree1 tree2   day
   <chr> <dbl> <chr> <chr> <dbl>
 1 BB     3435 SAP   ATK       3
 2 BB     3435 SAP   ATK       4
 3 BB     3435 SAP   ATK       5
 4 BB     3435 SAP   ATK       6
 5 DD     3434 ASP   ATK       2
 6 DD     3434 ASP   ATK       3
 7 DD     3434 ASP   ATK       4
 8 DD     3434 ASP   ATK       5
 9 DD     3435 SAP   ATK       1
10 DD     3435 SAP   ATK       3
11 DD     3435 SAP   ATK       5
12 DD     3435 SAP   ATK       7
13 ZZ     3434 ASP   ATK       1
14 ZZ     3434 ASP   ATK       2
15 ZZ     3434 ASP   ATK       6
16 ZZ     3434 ASP   ATK       8
17 ZZ     3435 SAP   ATK       2
18 ZZ     3435 SAP   ATK       4
19 ZZ     3435 SAP   ATK       6
20 ZZ     3435 SAP   ATK       8