2017-11-01 20 views
0

私は製品の類似性データを含む大きなスパース行列を得ました。 すべての製品は、xとyの両方で同じ順序で表示され、値が1の場合は、値が0の場合に製品が異なるかどうかにかかわらず、製品が同じであることを示します。R検索類似類似度スパース行列

次のように:この場合、P1に

P1 P2 P3 P4 
P1 1 1 0 0 
P2 0 1 0 1 
P3 0 0 1 1 
P4 0 1 0 1 

自体へとP2と同様であるが、P2はP4と同様です。最後にP1、P2、P4は同じです。

Product_Name Ref_Code 
    P1   P1 
    P2   P1 
    P3   P3 
    P4   P1 

それはRでそれを行うことは可能です: 私はP1、P2、P4に次のように同じコードが割り当てられますRで何かを書く必要がありますか?

乾杯、

ダリオ。

+0

がP4に似P3はありませんか?それはロジックごとにすべて同じになります。 – Prem

+0

申し訳ありませんが、コピーして貼り付けて元のアイデアを変更しました。 P3は他のものと似ていてはいけません –

答えて

1

あなたのロジックに従って@Premに同意しますが、すべての製品が同じです。私はreshape2パッケージを使用して製品を長い形式にするコード例を提供しました。たとえ類似性測度でも製品間に差異が生じない場合でも、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")])) 


}) 
0

別のアプローチは、可能性が

#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 

出力は次のようになります。

Product Product_Cluster 
1:  P1    1 
2:  P4    1 
3:  P2    1 
4:  P3    2 
5:  P5    2