如何将相关性或相似性 table 转换为 696x696 矩阵
How can I convert a correlation or similarity table to 696x696 matrix
所以这是 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 Index" 来计算项目之间的相似度。现在我在你可以在数据集中看到的地方。
数据集:数据集包含V1和V2中的material个数字。 N = 项目之间的相似性指数。数据集仅包含以相同顺序一起出现的一对项目。因此,有很多对不在数据集中。
我的 objective: 我有 696 个唯一的项目编号,范围从 1-696。我想要一个由 N 作为值的 696x696 矩阵。数据集中 "missing pairs" 的值应等于零 = 表示两个项目之间没有相似性。
我要用它做什么? 我想根据 696 个项目在同一顺序中出现的次数对它们进行聚类。
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")
所以这是 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 Index" 来计算项目之间的相似度。现在我在你可以在数据集中看到的地方。
数据集:数据集包含V1和V2中的material个数字。 N = 项目之间的相似性指数。数据集仅包含以相同顺序一起出现的一对项目。因此,有很多对不在数据集中。
我的 objective: 我有 696 个唯一的项目编号,范围从 1-696。我想要一个由 N 作为值的 696x696 矩阵。数据集中 "missing pairs" 的值应等于零 = 表示两个项目之间没有相似性。
我要用它做什么? 我想根据 696 个项目在同一顺序中出现的次数对它们进行聚类。
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")