当您有交易列,但有一个以上的项目列时,在R中使用规则进行关联规则

问题描述 投票:1回答:1

我正在尝试使用R中的库规则对数据集进行关联规则。该数据集具有一个交易列和5个项目列-我试图将数据转换为列表,然后使用规则,但是因为存在还有一个项目列,我不确定该怎么做。

我的数据集如下所示:

Transaction     Item1        Item2         Item3    

12/09/2001     lipstick      Bronzer        Mascara
2/09/2001     Eyeshadow     lipstick
13/09/2002     Powder        Remover
14/09/2003     Nail varnish  Lip gloss      Eyeliner 

我通常用于一个交易列和一个项目列的代码如下。

library(arules)
Transactions <- split(data$item, data$transaction)

basketanalysis <- as(Transactions, "transactions")

任何帮助将不胜感激。

r arules
1个回答
0
投票

这是我尝试过的。我认为您需要操纵数据并创建列表。首先,我创建了交易ID以防万一。然后,我将数据转换为长格式的数据帧。到这个时候,所有产品都停留在一个栏中。我删除了所有不适用的行。然后,我将产品转换为因子。对于每个组(交易ID),我创建了包含所有产品的列表。 x有一个称为whatever的列。这是您要用来创建交易对象的列表。

library(tidyverse)
library(arules)

mutate(mydata, transaction_id = 1:n()) %>% 
pivot_longer(cols = contains("Item"), names_to = "item", values_to = "product") %>% 
filter(complete.cases(product)) %>% 
mutate(product = factor(product)) %>% 
group_by(transaction_id) %>% 
summarize(whatever = list(product)) -> x

# Assign transaction ID as name to whatever
names(x$whatever) <- x$transaction_id

$`1`
[1] lipstick Bronzer  Mascara 
Levels: Bronzer Eyeliner Eyeshadow Lip gloss lipstick Mascara Nail varnish Powder Remover

$`2`
[1] Eyeshadow lipstick 
Levels: Bronzer Eyeliner Eyeshadow Lip gloss lipstick Mascara Nail varnish Powder Remover

$`3`
[1] Powder  Remover
Levels: Bronzer Eyeliner Eyeshadow Lip gloss lipstick Mascara Nail varnish Powder Remover

$`4`
[1] Nail varnish Lip gloss    Eyeliner    
Levels: Bronzer Eyeliner Eyeshadow Lip gloss lipstick Mascara Nail varnish Powder Remover

最后,我创建了一个事务类对象。

mybasket <- as(x$whatever, "transactions")

> summary(mybasket)
transactions as itemMatrix in sparse format with
 4 rows (elements/itemsets/transactions) and
 9 columns (items) and a density of 0.2777778 

most frequent items:
 lipstick   Bronzer  Eyeliner Eyeshadow Lip gloss   (Other) 
        2         1         1         1         1         4 

element (itemset/transaction) length distribution:
sizes
2 3 
2 2 

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   2.0     2.0     2.5     2.5     3.0     3.0 

includes extended item information - examples:
     labels
1   Bronzer
2  Eyeliner
3 Eyeshadow

includes extended transaction information - examples:
  transactionID
1             1
2             2
3             3

DATA

mydata <- structure(list(Transaction = c("12/09/2001", "2/09/2001", "13/09/2002", 
"14/09/2003"), Item1 = c("lipstick", "Eyeshadow", "Powder", "Nail varnish"
), Item2 = c("Bronzer", "lipstick", "Remover", "Lip gloss"), 
Item3 = c("Mascara", NA, NA, "Eyeliner")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))
© www.soinside.com 2019 - 2024. All rights reserved.