his*_*eim 6 r cluster-analysis dendrogram traminer
我使用以下R代码生成带有基于TraMineR序列的标签的树形图(参见附图):
library(TraMineR)
library(cluster)
clusterward <- agnes(twitter.om, diss = TRUE, method = "ward")
plot(clusterward, which.plots = 2, labels=colnames(twitter_sequences))
Run Code Online (Sandbox Code Playgroud)
完整代码(包括数据集)可以在这里找到.
由于树形图以图形方式提供信息,因此以文本和/或表格格式获取相同信息将非常方便.如果我调用对象clusterward的任何方面(由agnes创建),例如"order"或"merge",我会使用数字而不是我得到的名称来标记所有内容colnames(twitter_sequences)
.另外,我看不出如何输出树形图中以图形方式表示的分组.
总结一下:如何使用R以及理想情况下的电车/集群库正确显示标签,以文本/表格格式获取集群输出?
问题涉及cluster
包裹。agnes.object
返回的帮助页面agnes
(参见http://stat.ethz.ch/R-manual/R-devel/library/cluster/html/agnes.object.html)指出该对象包含一个order.lab
组件“类似于order
,但包含观察标签而不是观察编号。仅当原始观察被标记时,此组件才可用。”
TraMineR 生成的相异矩阵(twitter.om
在您的情况下)当前不保留序列标签作为行和列名称。要获取order.lab
组件,您必须手动将序列标签指定为矩阵的rownames
和。我在这里用TraMineR 包提供的数据进行说明。colnames
twitter.om
mvad
library(TraMineR)
data(mvad)
## attaching row labels
rownames(mvad) <- paste("seq",rownames(mvad),sep="")
mvad.seq <- seqdef(mvad[17:86])
## computing the dissimilarity matrix
dist.om <- seqdist(mvad.seq, method = "OM", indel = 1, sm = "TRATE")
## assigning row and column labels
rownames(dist.om) <- rownames(mvad)
colnames(dist.om) <- rownames(mvad)
dist.om[1:6,1:6]
## Hierarchical cluster with agnes library(cluster)
cward <- agnes(dist.om, diss = TRUE, method = "ward")
## here we can see that cward has an order.lab component
attributes(cward)
Run Code Online (Sandbox Code Playgroud)
这是为了获取order
序列标签而不是数字。但现在我不清楚您想要文本/表格形式的集群结果。根据树状图,您决定要在哪里切割它,即您想要的组数,并使用 切割树状图cutree
,例如cl.4 <- cutree(clusterward1, k = 4)
。结果cl.4
是一个向量,其中包含每个序列的簇成员资格,并且您可以获得组 1 的成员列表,例如,使用rownames(mvad.seq)[cl.4==1]
。
或者,您可以使用该identify
方法(请参阅?identify.hclust
)从图中以交互方式选择组,但需要将参数传递为 as.hclust(cward)
。这是示例的代码
## plot the dendrogram
plot(cward, which.plot = 2, labels=FALSE)
## and select the groups manually from the plot
x <- identify(as.hclust(cward)) ## Terminate with second mouse button
## number of groups selected
length(x)
## list of members of the first group
x[[1]]
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。