使用cutree从hclust获取联接的行

时间:2019-05-02 17:38:10

标签: r

我沿用这些代码:

library(dplyr)
library(fuzzywuzzyR)
library(proxy)
library(stringdist)

set.seed(42)
rm(list = ls())
options(scipen = 999)

#init = FuzzMatcher$new()

data <- data.frame(string = c("world hello", "hello world", "hello vorld", "hello world 1", "hello world", "hello world hello world"))
data$string <- as.character(data$string)

distance_function <- function(string_1, string_2) {
    #init$Token_set_ratio(string1 = string_1, string2 = string_2)
    stringdist(string_1, string_2, method = "qgram")
}

combinations <- combn(nrow(data), 2)
distances <- matrix(, nrow = 1, ncol = ncol(combinations))

distance_matrix <- matrix(0, nrow = nrow(data), ncol = nrow(data), dimnames = list(data$string, data$string))

for (i in 1:ncol(combinations)) {

    distance <- distance_function(data[combinations[1, i], 1], data[combinations[2, i], 1])

    #print(data[combinations[1, i], 1])
    #print(data[combinations[2, i], 1])
    #print(distance)

    distance_matrix[combinations[1, i], combinations[2, i]] <- distance
    distance_matrix[combinations[2, i], combinations[1, i]] <- distance

}

hclust <- hclust(dist(1 - distance_matrix), method = "ward.D2")

plot(hclust)

我可以使用以下命令对字符串进行“一维”排序:

hclust$labels[c(hclust$order)]

我还想根据可以使用以下方法生成的树状图附加要连接的字符串的信息:

plot(hclust)

我知道美眉,但在这里感觉不对(例如,使用h参数或k)。希望有道理吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试

rapply(as.dendrogram(hclust), function(x) attr(x, "label"), how = "list")
# [[1]]
# [1] "hello world hello world"
# 
# [[2]]
# [[2]][[1]]
# [1] "hello vorld"
# 
# [[2]][[2]]
# [[2]][[2]][[1]]
# [1] "hello world 1"
#
# [[2]][[2]][[2]]
# [[2]][[2]][[2]][[1]]
# [1] "hello world"
#
# [[2]][[2]][[2]][[2]]
# [[2]][[2]][[2]][[2]][[1]]
# [1] "world hello"
#
# [[2]][[2]][[2]][[2]][[2]]
# [1] "hello world"

为您提供嵌套列表。