交易数据

R 中的购物篮分析

Christopher Bruffaerts

Statistician

什么是交易?

交易(Transaction):买卖某物的行为。

transaction

交易数据(Transactional data): 某位顾客在一次购买中买到的全部商品列表。

单笔交易示例:

  TID Product
1   1   Bread
2   1  Cheese
3   1  Cheese
4   1  Cheese
R 中的购物篮分析

R 中的交易类

Transactions 类: 表示用于挖掘项集或规则的交易数据。

可由以下强制转换:

  • 列表
  • 矩阵
  • 数据框

但需先准备好数据。

处理交易数据时要点

  • 用于标识产品的字段/列

  • 用于标识交易的字段/列

R 中的购物篮分析

回到杂货店(1)

门店的交易数据

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
R 中的购物篮分析

回到杂货店(2)

用 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
R 中的购物篮分析

回到杂货店(3)

转换为 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
R 中的购物篮分析

更多交易检查

交易概览

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)
R 中的购物篮分析

交易概览

绘制 ItemMatrix

image(data_trx)

警告:仅对少量交易使用该函数

有助于识别:

  • 交易中的模式
  • 数据稀疏性

密度 = 18/28 = 0.64

trx_image

R 中的购物篮分析

让我们检查交易!

R 中的购物篮分析

Preparing Video For Download...