根据 R 中的属性对元素列表进行分类

Classify a list of element based on their attribute in R

我有一个列表元素,每个元素都包含一个文本属性列表,例如 。

> list
[[1]]
 [1] "attribute 1"     
 [2] "attribute 2"     
 [3] "attribute 3"     

[[2]]
[1] "attribute 4"     
[2] "attribute 5" 
[3] "attribute 6" 

[[3]]
 [1] "attribute 1"     
 [2] "attribute 2"      

[[4]]
[1] "attribute 4"     
[2] "attribute 5"
[3] "attribute 6" 

我可以应用什么分类或聚类算法(最简单的)来根据其文本属性的相似性对该元素进行分类。
获得如下结果:[1,3] in category 1 and [2,4] in category 2。

想法

您可以在距离矩阵上使用 hclust。为此,您首先需要将数据转换为矩阵,计算距离,然后对该矩阵进行层次聚类。

代码

l <- list(paste("attribute", 1:3),
          paste("attribute", 4:6),
          paste("attribute", 1:2),
          paste("attribute", 4:6))
allElem <- sort(unique(unlist(l)))
incidM <- do.call(rbind, lapply(l, function(x) as.numeric(allElem %in% x)))
colnames(incidM) <- allElem
rownames(incidM) <- paste("Set", seq_len(NROW(incidM)))
dM <- dist(incidM)
hc <- hclust(dM)
plot(hc)

说明

首先,您创建一个矩阵,其中的行对应于列表中的元素,行对应于列表中的唯一值。如果相应的列表元素包含此属性,则每个元素为 1,否则为 0

incidM
#       attribute 1 attribute 2 attribute 3 attribute 4 attribute 5 attribute 6
# Set 1           1           1           1           0           0           0
# Set 2           0           0           0           1           1           1
# Set 3           1           1           0           0           0           0
# Set 4           0           0           0           1           1           1

然后,您可以计算行之间的距离矩阵,并对该矩阵进行层次聚类。最后,您可以绘制整个图,您确实会看到第 1 组和第 3 组与第 2 组和第 4 组相似。