R-搜索交叉相似稀疏矩阵

R-搜索交叉相似稀疏矩阵,r,sparse-matrix,R,Sparse Matrix,我有一个包含产品相似性数据的大型稀疏出现矩阵。 所有产品在x和y上的显示顺序相同,值为1表示产品相同,值为0表示产品不同 详情如下: P1 P2 P3 P4 P1 1 1 0 0 P2 0 1 0 1 P3 0 0 1 1 P4 0 1 0 1 在这种情况下,P1与自身和P2相似,但P2与P4相似。最后P1,P2和P4是一样的。 我需要在R中写一些东西,将分配给P1、P2和P4相同的代码,如下所示: Product_Name Re

我有一个包含产品相似性数据的大型稀疏出现矩阵。 所有产品在x和y上的显示顺序相同,值为1表示产品相同,值为0表示产品不同

详情如下:

P1  P2  P3  P4
P1  1   1   0   0
P2  0   1   0   1
P3  0   0   1   1
P4  0   1   0   1
在这种情况下,P1与自身和P2相似,但P2与P4相似。最后P1,P2和P4是一样的。 我需要在R中写一些东西,将分配给P1、P2和P4相同的代码,如下所示:

Product_Name  Ref_Code 
     P1          P1
     P2          P1
     P3          P3
     P4          P1
可以用R做吗

干杯


Dario.

我同意@Prem,按照您的逻辑,所有产品都是相同的。我提供了一个代码示例,使用Reforme2Package将您的产品转换为长格式。即使您的相似性度量不会在产品之间产生任何差异,您也可以使用melt的输出,以不同的方式对相似性数据进行排序和过滤,从而实现您想要的结果

library(reshape2)

data <- read.table ( text = "P1  P2  P3  P4
                          P1  1   1   0   0
                          P2  0   1   0   1
                          P3  0   0   1   1
                          P4  0   1   0   1"
                          , header = TRUE, stringsAsFactors = FALSE)


data <-cbind(rownames(data), data)
names(data)[1] <- "product1"

data.melt <- melt(data
             , id.vars = "product1"
             , measure.vars = colnames(data)[2:ncol(data)]
             , variable.name = "product2"
             , value.name = "similarity"
             ,factorsAsStrings = TRUE)

#check the output of melt, maybe the long format is suitable for your task    
data.melt

#if you split the data by your similarity and check the unique products
#in each list, you will see that they are all the same
data.split <- split(data.melt, data.melt$similarity)

lapply(data.split, function(x) {

  unique(unlist(x[, c("product1", "product2")]))


})

另一种方法可以是

#sample data (to understand this approach better I have slightly modified your input data)
mat <- Matrix(data = c(1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1), nrow = 5, ncol = 5,
              dimnames = list(c("P1","P2","P3","P4","P5"),c("P1","P2","P3","P4","P5")),
              sparse = TRUE)
mat

#create dataframe having relationship among similar products
mat_summary <- summary(mat)
df <- data.frame(Product_Name = rownames(mat)[mat_summary$i],
                 Similar_Product_Name = colnames(mat)[mat_summary$j])
df <- df[df$Product_Name != df$Similar_Product_Name, ]
df

#clustering - to get the final result
library(igraph)
library(data.table)
df.g <- graph.data.frame(df)
final_df <- setNames(setDT(as.data.frame(clusters(df.g)$membership), keep.rownames = TRUE)[], c('Product', 'Product_Cluster'))
final_df

P3和P4不是很相似吗?按照逻辑,一切都是一样的。对不起,复制和粘贴改变了原来的想法。P3不应与其他任何内容相似
   Product Product_Cluster
1:      P1               1
2:      P4               1
3:      P2               1
4:      P3               2
5:      P5               2