Co-occurrence matrix using SAC?

人盡茶涼 提交于 2019-12-01 10:57:02

As @joran mentioned its kind of unclear what you really want. But If I understand correctly(probably not) I would like to propose an alternate route. I think you want a matrix of items to items with numbers representing the number of times the items share a customer?

If so then:

library(igraph)
library(tnet)
id_item<-cbind(
i=c(1,1,2,2,2,2,2,3,4,5,5,5,6,6,7,8),  #items
p=c(1,2,1,2,3,4,5,2,3,4,5,6,6,7,8,8))  #customers
item_item<-projecting_tm(id_item, method="sum")
item_item <- tnet_igraph(item_item,type="weighted one-mode tnet")
itemmat<-get.adjacency(item_item,attr="weight")
itemmat  #8x8 martrix of items to items

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,]    0    2    1    0    0    0    0    0
#[2,]    2    0    1    1    2    0    0    0
#[3,]    1    1    0    0    0    0    0    0
#[4,]    0    1    0    0    0    0    0    0
#[5,]    0    2    0    0    0    1    0    0
#[6,]    0    0    0    0    1    0    0    0
#[7,]    0    0    0    0    0    0    0    1
#[8,]    0    0    0    0    0    0    1    0

If you need to take number of times the item was bought (volume) into account too then this is easily added into this code.

rehsape2 provides 'acast', which might be what you want:

> acast(x, id~item,value.var='volume')
  c1 c2 c3 c4 c5 c6 c8 c9
a  2  3  2  1  4 NA NA NA
b  2  6  1  4 NA  6 NA NA
c NA  5 NA NA NA NA  6  2
d  1 NA NA NA NA NA NA NA
e  2  3  7  1 NA NA NA  5
f  7 NA  1 NA NA NA NA NA

reshape2::dcast produces a data frame, if that is more convenient.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!