问题
I have the following data frame 'x'
id,item,volume
a,c1,2
a,c2,3
a,c3,2
a,c4,1
a,c5,4
b,c6,6
b,c1,2
b,c3,1
b,c2,6
b,c4,4
c,c2,5
c,c8,6
c,c9,2
d,c1,1
e,c3,7
e,c2,3
e,c1,2
e,c9,5
e,c4,1
f,c1,7
f,c3,1
The first column is the id of a customer, the second column is the id of an item that customer bought and the third column is the number of those items bought. I'm trying to create a co-occurrence matrix which is a square matrix with 8 rows and columns, 8 being the number of distinct items.
n = length(unique(x$cid))
Could this be done through a SAC paradigm? For every id, I need to update the above matrix by adding +1 for every combination. For example for user 'b' with items c1,c2,c3,c4,c6, the 1st row in the matrix for columns 2,3,4 & 6 should be incremented by 1 and so on for all users. I'm unable to cast it into this framework. Any help much appreciated.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/10568540/co-occurrence-matrix-using-sac