我有一个混合数据集(分类和连续变量),我想使用Gower distance进行层次聚类。
我的代码基于https://www.r-bloggers.com/hierarchical-clustering-in-r-2/的一个例子,它使用基本R dist()
作为欧几里德距离。由于dist()
不计算Gower距离,我尝试使用philentropy::distance()
来计算它,但它不起作用。
谢谢你的帮助!
# Data
data("mtcars")
mtcars$cyl <- as.factor(mtcars$cyl)
# Hierarchical clustering with Euclidean distance - works
clusters <- hclust(dist(mtcars[, 1:2]))
plot(clusters)
# Hierarchical clustering with Gower distance - doesn't work
library(philentropy)
clusters <- hclust(distance(mtcars[, 1:2], method = "gower"))
plot(clusters)
错误发生在distance
函数本身。
我不知道它是否有意,但philentropy::distance
的当前实现与“gower”方法无法处理任何混合数据类型,因为第一个操作是转置data.frame,产生一个字符矩阵然后抛出传递给DistMatrixWithoutUnit
函数时输入错误。
您可以尝试使用daisy
中的cluster
函数。
library(cluster)
x <- mtcars[,1:2]
x$cyl <- as.factor(x$cyl)
dist <- daisy(x, metric = "gower")
cls <- hclust(dist)
plot(cls)
编辑:为了将来参考,似乎philentropy
将更新为包括下一版本中更好的类型处理。来自vignette
在未来的philentropy版本中,我将优化distance()函数,以便内部检查数据类型正确性和正确的输入数据将比基本dist()函数花费更少的终止时间。
LLL;对不起,我不懂英文,我无法解释。现在这是一个尝试。但代码很好;-)
library(philentropy)
clusters <- hclust(
as.dist(
distance(mtcars[, 1:2], method = "gower")))
plot(clusters)
好看
使用gower
包可以非常有效地完成它
library(gower)
d <- sapply(1:nrow(mtcars), function(i) gower_dist(mtcars[i,],mtcars))
d <- as.dist(d)
h <- hclust(d)
plot(h)
非常感谢这个伟大的问题,感谢所有提供优秀答案的人。
只是为了解决未来读者的问题:
# import example data
data("mtcars")
# store example subset with correct data type
mtcars_subset <- tibble::tibble(mpg = as.numeric(as.vector(mtcars$mpg)),
cyl = as.numeric(as.vector(mtcars$cyl)),
disp = as.numeric(as.vector(mtcars$disp)))
# transpose data.frame to be conform with philentropy input format
mtcars_subset <- t(mtcars_subset)
# cluster
clusters <- hclust(as.dist(philentropy::distance(mtcars_subset, method = "gower")))
plot(clusters)
# When using the developer version on GitHub you can also specify 'use.row.names = TRUE'
clusters <- hclust(as.dist(philentropy::distance(mtcars_subset, method = "gower",
use.row.names = TRUE)))
plot(clusters)
如您所见,聚类现在可以完美地运行。
问题是在示例数据集中,列cyl
存储factor
值,而不是double
函数所需的philentropy::distance()
值。由于底层代码是用Rcpp
编写的,因此不符合数据类型会导致问题。正如Esther正确指出的那样,我将在未来版本的软件包中实现更好的方法来检查类型安全性。
head(tibble::as.tibble(mtcars))
# A tibble: 6 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21 6 160 110 3.9 2.62 16.5 0 1 4 4
2 21 6 160 110 3.9 2.88 17.0 0 1 4 4
3 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
4 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
5 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
6 18.1 6 225 105 2.76 3.46 20.2 1 0 3 1
为了克服这个限制,我将mtcars
数据集中感兴趣的列存储在单独的data.frame / tibble中,并通过as.numeric(as.vector(mtcars$mpg))
将所有列转换为double值。
结果子集data.frame现在仅根据需要存储double
值。
mtcars_subset
# A tibble: 32 x 3
mpg cyl disp
<dbl> <dbl> <dbl>
1 21 6 160
2 21 6 160
3 22.8 4 108
4 21.4 6 258
5 18.7 8 360
6 18.1 6 225
7 14.3 8 360
8 24.4 4 147.
9 22.8 4 141.
10 19.2 6 168.
# … with 22 more rows
还请注意,如果仅提供philentropy::distance()
函数2个输入向量,则只返回一个距离值,并且hclust()
函数将无法计算具有一个值的任何聚类。因此,我添加了第三列disp
以实现群集的可视化。
我希望这有帮助。