我想根据计数过滤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|
这是我的预期输出。我想按计数过滤出两个最大的品牌,然后找到每个品牌/类别组合中的平均点击次数
|Brand | Category| mean_clicks|
|:-----|--------:|-----------:|
|A | 1| 12.0|
|A | 2| 14.0|
|B | 1| 15.0|
|B | 2| 11.5|
我以为这样的代码可以实现(但不能)
df %>%
group_by(Brand, Category) %>%
top_n(2, Brand) %>% # Largest 2 brands by count
summarise(mean_clicks = mean(Clicks))
编辑:理想的答案应该能够在数据库表以及本地表上使用
答案 0 :(得分:4)
使用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
答案 1 :(得分:3)
另一种dplyr
解决方案:
df %>%
group_by(Brand) %>%
mutate(n = n()) %>%
ungroup() %>%
mutate(rank = dense_rank(desc(n))) %>%
filter(rank == 1 | rank == 2) %>%
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.0
2 A 2. 14.0
3 B 1. 15.0
4 B 2. 11.5
或简化版本(基于@camille的建议):
df %>%
group_by(Brand) %>%
mutate(n = n()) %>%
ungroup() %>%
filter(dense_rank(desc(n)) < 3) %>%
group_by(Brand, Category) %>%
summarise(mean_clicks = mean(Clicks))
答案 2 :(得分:2)
编辑
基于更新后的问题,我们可以先添加一个计数列,仅过滤排名靠前的n
组计数,然后过滤group_by
Brand
和Category
来找到{{1 }}。
mean
原始答案
我们可以df %>%
add_count(Brand, sort = TRUE) %>%
filter(n %in% head(unique(n), 2)) %>%
group_by(Brand, Category) %>%
summarise(mean_clicks = mean(Clicks))
# Brand Category mean_clicks
# <fct> <dbl> <dbl>
#1 A 1 12
#2 A 2 14
#3 B 1 15
#4 B 2 11.5
group_by
并按组进行所有计算,然后按Brand
过滤顶部组
top_n
答案 3 :(得分:0)
data.table的想法是获取按Brands
分组的计数并过滤前两个(按降序排列)。然后,我们将其与原始数据框合并,并找到按(Brand, Category)
library(data.table)
#Convert to data.table
dt1 <- setDT(df)
dt1[dt1[, .(cnt = .N), by = Brand][
order(cnt, decreasing = TRUE), .SD[1:2]][,cnt := NULL],
on = 'Brand'][, .(means = mean(Clicks)), by = .(Brand, Category)][]
给出,
Brand Category means 1: A 1 12.0 2: A 2 14.0 3: B 2 11.5 4: B 1 15.0
答案 4 :(得分:0)
如何使用table
从基数R开始使用这种方法-
df %>%
filter(Brand %in% names(tail(sort(table(Brand)), 2))) %>%
group_by(Brand, Category) %>%
summarise(mean_clicks = mean(Clicks))
# A tibble: 4 x 3
# Groups: Brand [?]
Brand Category mean_clicks
<chr> <dbl> <dbl>
1 A 1.00 12.0
2 A 2.00 14.0
3 B 1.00 15.0
4 B 2.00 11.5
答案 5 :(得分:0)
df %>% count(Brand) %>% top_n(2,n) -> Top2
df %>% group_by(Brand, Category) %>%
filter(Brand %in% Top2$Brand) %>%
summarise(mean_clicks = mean(Clicks))
remove(Top2)