【问题标题】:How can I convert a correlation or similarity table to 696x696 matrix如何将相关性或相似性表转换为 696x696 矩阵
【发布时间】:2018-11-05 11:51:03
【问题描述】:

这是 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中的材料编号。 N = 项目之间的相似性指数。数据集仅包含以相同顺序一起出现的一对项目。因此,有很多对不在数据集中。

我的目标:我有 696 个唯一的项目编号,范围从 1 到 696。我想要一个 N 的 696x696 矩阵作为值。数据集中“缺失对”的值应等于 0 = 表示两项之间没有相似性。

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

【问题讨论】:

  • 在将变量V1V2设置为因子后(将levels设置为你想要的,即1:696),你可以使用xtabs( N ~ V1 + V2, mat, sparse=TRUE
  • 你能再解释一下吗?我是一个完全的初学者。如何将级别设置为 1:696?

标签: r cluster-analysis distance correlation similarity


【解决方案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")

【讨论】:

  • 谢谢,它成功了。不幸的是,它对集群没有帮助。所以必须重新开始。我知道这是一个不同的问题,但您知道如何在 R 中执行此操作:dataanalytics.org.uk/Publications/S4E2e%20Support/exercises/…
  • 嗨,@MA;抱歉,没有。我真的没有相似性/聚类的经验。顺便说一句,stats.stackexchange.com 可能有助于获得有关此类事情的建议 - 但请务必充分解释您的初始数据以及您想要从中提取的信息。
猜你喜欢
  • 1970-01-01
  • 2022-01-02
  • 2023-03-28
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多