Tidyverse:过滤分组数据帧中的n个最大组

Shi*_*obe 10 r top-n dplyr

我想根据计数过滤n个最大的组,然后对过滤的数据帧进行一些计算

这是一些数据

Brand <- c("A","B","C","A","A","B","A","A","B","C")
Category <- c(1,2,1,1,2,1,2,1,2,1)
Clicks <- c(10,11,12,13,14,15,14,13,12,11)
df <- data.frame(Brand,Category,Clicks)

|Brand | Category| Clicks|
|:-----|--------:|------:|
|A     |        1|     10|
|B     |        2|     11|
|C     |        1|     12|
|A     |        1|     13|
|A     |        2|     14|
|B     |        1|     15|
|A     |        2|     14|
|A     |        1|     13|
|B     |        2|     12|
|C     |        1|     11|
Run Code Online (Sandbox Code Playgroud)

这是我的预期输出.我想按计数过滤掉两个最大的品牌,然后找出每个品牌/类别组合的平均点击次数

|Brand | Category| mean_clicks|
|:-----|--------:|-----------:|
|A     |        1|        12.0|
|A     |        2|        14.0|
|B     |        1|        15.0|
|B     |        2|        11.5|
Run Code Online (Sandbox Code Playgroud)

我认为可以用这样的代码实现(但不能)

df %>%
  group_by(Brand, Category) %>%
  top_n(2, Brand) %>% # Largest 2 brands by count
  summarise(mean_clicks = mean(Clicks))
Run Code Online (Sandbox Code Playgroud)

编辑:理想的答案应该能够用于数据库表和本地表

Pau*_*aul 6

另一种dplyr使用join过滤数据帧的解决方案:

library(dplyr)

df %>%
  group_by(Brand) %>%
  summarise(n = n()) %>%
  top_n(2) %>% # select top 2
  left_join(df, by = "Brand") %>% # filters out top 2 Brands
  group_by(Brand, Category) %>%
  summarise(mean_clicks = mean(Clicks))

# # A tibble: 4 x 3
# # Groups:   Brand [?]
#   Brand Category mean_clicks
#   <fct>    <dbl>       <dbl>
# 1 A            1        12  
# 2 A            2        14  
# 3 B            1        15  
# 4 B            2        11.5
Run Code Online (Sandbox Code Playgroud)