如何将相关或相似性表转换为696x696矩阵

时间:2018-05-26 06:36:36

标签: r cluster-analysis distance correlation similarity

所以这是pastebin中的完整数据集:https://pastebin.com/xpGMsSSf

快速按下pastebin:

`"V1","V2","N"
16,17,0.065532029
16,30,0.070163826
17,30,0.053089888
29,30,0.068024596`

数据的预处理:我从每个订单中的客户订单和商品列表开始。我计算了同一订单中每对项目的出现次数。然后,我使用“Jackkard指数”来计算项目之间的相似性。现在,我可以在数据集中看到。

数据集:数据集包含V1和V2中的材料编号。 N =项目之间的相似性指数。数据集仅包含以相同顺序一起出现的一对项目。因此,很多对都不在数据集中。

我的目标:我有696个唯一商品编号,范围是1-696。我想用N96作为值的696x696矩阵。数据集中“缺失对”的值应等于零=表示两个项目之间没有相似性。

我打算将它用于什么?我想根据同一订单中的出现次数对696项进行聚类。

1 个答案:

答案 0 :(得分:1)

xtabs可用于以您想要的形式获取数据 - 它还具有很好的功能,您可以将结果指定为稀疏矩阵(您的(nrow(dat)/696^2

dat <- read.csv("https://pastebin.com/raw/xpGMsSSf")

# setting to factor introduces factor levels that are not found in the data
# see below for what is being done
dat[c("V1", "V2")] <- lapply(dat[c("V1", "V2")], factor, levels=1:696)

out <- xtabs( N ~ V1 + V2, dat, sparse=TRUE)

out[1:5, 1:5]

# To make symmetric
library(Matrix)
out[lower.tri(out)] <- t(out)[lower.tri(out)]
# Explanation of setting common factor levels
# example
x = c(1,2,3)
y = c(1,4,5)
table(x, y)
# but if we want both row and columns of table to include 1 to 5
# we can set to factor
x = factor(x, levels=1:5)
y = factor(y, levels=1:5)
table(x, y)
dput(head(mat))
structure(list(V1 = c(16L, 16L, 17L, 29L, 16L, 17L), V2 = c(17L, 
30L, 30L, 30L, 29L, 29L), N = c(0.065532029, 0.070163826, 0.053089888, 
0.068024596, 0.053083392, 0.041870099)), .Names = c("V1", "V2", 
"N"), row.names = c(NA, 6L), class = "data.frame")