非常感谢这个好问题,感谢所有提供出色答案的人。
只是为了为未来的读者解决问题:
# 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 值,而不是philentropy::distance() 函数所需的double 值。由于底层代码是用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)) 将所有列转换为双精度值。
生成的子集 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 以启用集群的可视化。
我希望这会有所帮助。