我使用的代码是这样的:
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)我知道cutree,但这里感觉不对(例如,使用h参数或k)。希望这是有意义的?
发布于 2019-05-03 05:38:11
你可以试一试
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"这给了你一个嵌套的列表。
https://stackoverflow.com/questions/55957600
复制相似问题