R 中的购物篮分析
Christopher Bruffaerts
Statistician
商店里有什么?

篮子 1:{"Bread", "Cheese"}
篮子 2:{"Bread", "Wine" , "Cheese"}
多个篮子
若有 100 位顾客进店,能否找到一起出现的商品关联?
示例:Bread 和 Cheese

结果:"若此,则彼"
从多个篮子中学习

不同应用
创建一个包含多个篮子的数据集!
my_baskets = data.frame(
"Basket" = c(1,1,1,1, 2,2,2, 3,3, 4,4,4, 5,5, 6,6, 7,7),
"Product" = c("Bread", "Cheese", "Cheese", "Cheese",
"Bread", "Butter", "Wine",
"Butter", "Butter",
"Butter", "Wine", "Wine",
"Butter", "Cheese",
"Cheese", "Wine",
"Wine", "Wine")
)
我的篮子一瞥
head(my_baskets)
Basket Product
1 1 Bread
2 1 Cheese
3 1 Cheese
4 1 Cheese
5 2 Bread
6 2 Butter
问题
n_distinct(my_baskets$Product)
[1] 4
n_distinct(my_baskets$Basket)
[1] 7
df_basket =
my_baskets %>%
group_by(Basket) %>%
summarize(
n_total = n(),
n_items = n_distinct(Product))
Basket n_total n_items
<dbl> <int> <int>
1 1 4 2
2 2 3 3
平均篮子大小
basket_size %>%
summarize(
avg_total_items = mean(n_total),
avg_dist_items = mean(n_items))
# A tibble: 1 x 2
avg_total_items avg_dist_items
<dbl> <dbl>
1 2.57 1.86
篮子大小分布
# 不同商品数的分布
ggplot(df_basket, aes(n_items)) +
geom_bar()

在看哪个商品?
某商品在所有篮子中出现了多少次?
有多少个篮子包含该商品?
示例:

在 R 中筛选 Cheese
# 包含 Cheese 的篮子数
my_baskets %>%
filter(Product == "Cheese") %>%
summarize(
n_tot_items = n(),
n_basket_item = n_distinct(Basket))
n_tot_items n_basket_item
1 5 3
关联规则挖掘:在一组商品中发现经常共同出现的关联。

规则提取示例:
课程剩余部分计划:

R 中的购物篮分析