R 中的购物篮分析
Christopher Bruffaerts
Statistician
交易(Transaction):买卖某物的行为。

交易数据(Transactional data): 某位顾客在一次购买中买到的全部商品列表。
单笔交易示例:
TID Product
1 1 Bread
2 1 Cheese
3 1 Cheese
4 1 Cheese
Transactions 类: 表示用于挖掘项集或规则的交易数据。
可由以下强制转换:
但需先准备好数据。
处理交易数据时要点
用于标识产品的字段/列
用于标识交易的字段/列
门店的交易数据
my_transactions = data.frame(
"TID" = 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_transactions, 10)
TID Product
1 1 Bread
2 1 Butter
3 1 Cheese
4 1 Wine
5 2 Bread
6 2 Butter
7 2 Wine
8 3 Bread
9 3 Butter
10 4 Butter
用 split 函数创建列表
# 将 TID 转为因子
my_transactions$TID =
factor(my_transactions$TID)
# 按组拆分
data_list = split(my_transactions$Product,
my_transactions$TID)
data_list
$`1`
[1] Bread Butter Cheese Wine
Levels: Bread Butter Cheese Wine
$`2`
[1] Bread Butter Wine
Levels: Bread Butter Cheese Wine
$`3`
[1] Bread Butter
Levels: Bread Butter Cheese Wine
转换为 transaction 类
# 转为交易数据集
data_trx = as(data_list,"transactions")
# 查看交易
inspect(data_trx)
交易数据预览
items transactionID
[1] {Bread,Butter,Cheese,Wine} 1
[2] {Bread,Butter,Wine} 2
[3] {Bread,Butter} 3
[4] {Butter,Cheese,Wine} 4
[5] {Butter,Cheese} 5
[6] {Cheese,Wine} 6
[7] {Butter,Wine} 7
交易概览
inspect(head(data_trx))
items transactionID
[1] {Bread,Butter,Cheese,Wine} 1
[2] {Bread,Butter,Wine} 2
[3] {Bread,Butter} 3
[4] {Butter,Cheese,Wine} 4
[5] {Butter,Cheese} 5
[6] {Cheese,Wine} 6
访问特定交易
inspect(data_trx[1])
inspect(data_trx[1:3])
交易对象摘要
summary(data_trx)
绘制 ItemMatrix
image(data_trx)
警告:仅对少量交易使用该函数
有助于识别:
密度 = 18/28 = 0.64

R 中的购物篮分析