创建条件百分比矩阵

Creating a matrix of conditional percentages

首先,我已经能够将一个嵌套的 for 循环放在一起来创建我想要的对象,它适用于小型玩具数据集,但我将要处理的数据通常是更大,我正在尝试确定 R 中是否存在具有完成此任务的内置函数的包。

最终对象是一个数据框或矩阵,它显示给定参考行的列中的条件百分比。这是玩具数据的代码和生成最终输出对象的嵌套 for 循环。

mylist <- list(
ID001=c("apple","orange","grape"),
ID002=c("banana","grape"),
ID003=c("apple","pineapple"),
ID004=c("orange","apple"),
ID005=c("orange","grape", "apple"))

dat <- reshape2:::melt(mylist)
names(dat) <- c("fruit","id")
dat <- dat[,c(2,1)]

theFruit <- unique(dat$fruit)
n=length(theFruit)
final.df <- data.frame(matrix(nrow=n,ncol=n, dimnames=list(theFruit,theFruit)))

for(i in theFruit){
    for(j in theFruit){
        tempid1 <- dat[dat$fruit==i,]$id
        tempid2 <- dat[dat$fruit==j,]$id
        final.df[i,j] <- round(length(which(tempid1%in%tempid2))/length(tempid1),2)
    }
}

final.df

          apple orange grape banana pineapple
apple      1.00   0.75  0.50   0.00      0.25
orange     1.00   1.00  0.67   0.00      0.00
grape      0.67   0.67  1.00   0.33      0.00
banana     0.00   0.00  1.00   1.00      0.00
pineapple  1.00   0.00  0.00   0.00      1.00

阅读输出我们看到,给定一个人吃了一个苹果(苹果行),75% 的人也吃了一个橙子(橙色列)。同样,给定一个人吃了一个橙子(橙色行)100% 也吃了一个苹果(苹果列)。这不是为了与吃的两个水果的交点对称,它是以行为条件的列。

这似乎类似于购物篮分析应用程序,过去几天我一直在使用 arules 包来实现这一点。在 arules 包的白话中,我会说填充数据框的百分比的名称是支持值,但我无法从 arules 生成所有支持百分比的矩阵或数据框。

我将要处理的数据将有几百万个 ID,但只有大约 150 个 "products",因此输出矩阵只有大约 150x150。我可以使用规则来识别引人注目的成对关系,但有兴趣查看所有条件。

有谁知道 arules 或其他包是否可以完成这个?

您正在寻找 置信度 值 (Wikipedia)。使用 arules:

你会得到与你类似的输出
library(arules)
library(reshape2)
trans <- as(mylist, "transactions")
rules <- apriori(trans, parameter = list(supp = 0, conf = 0, minlen=2, maxlen=2))
df <- inspect(rules)[, c("lhs", "rhs", "confidence")]
dcast(df, lhs~rhs, value.var="confidence", fill=1)
#           lhs   {apple}  {banana}   {grape}  {orange} {pineapple}
# 1     {apple} 1.0000000 0.0000000 0.5000000 0.7500000        0.25
# 2    {banana} 0.0000000 1.0000000 1.0000000 0.0000000        0.00
# 3     {grape} 0.6666667 0.3333333 1.0000000 0.6666667        0.00
# 4    {orange} 1.0000000 0.0000000 0.6666667 1.0000000        0.00
# 5 {pineapple} 1.0000000 0.0000000 0.0000000 0.0000000        1.00

当然,您可以将第一列设为行名,稍后将数据框转换为矩阵。我把它留给你。