r - 使用 facetwrap 的多个 Kmeans 聚类和绘图
问题描述
我想问一下如何为同一数据集自动化多个 K-means 聚类 - 我想在聚类数量发生变化时创建多个 kmean 聚类,然后使用绘制结果facet_wrap
因此,人们可以观察一下似乎最合适的簇数。
我可以这样做,因为代码非常手动 - 它可以以某种方式自动化:
library(tidyverse)
Y <- mtcars %>% select(hp, disp)
kme1 <- kmeans(Y, 3)
kme2 <- kmeans(Y, 4)
kme3 <- kmeans(Y, 5)
kme4 <- kmeans(Y, 6)
A <- broom::augment(kme1, Y) %>%
mutate(num_clust = 3)
B <- broom::augment(kme2, Y) %>%
mutate(num_clust = 4)
C <- broom::augment(kme3, Y) %>%
mutate(num_clust = 5)
D <- broom::augment(kme4, Y) %>%
mutate(num_clust = 6)
rbind(A, B, C, D) %>%
ggplot(aes(hp, disp)) +
geom_point(aes(color = .cluster)) +
stat_ellipse(aes(x=hp,y=disp,fill=factor(.cluster)),
geom="polygon", level=0.95, alpha=0.2) +
facet_wrap(~num_clust)
解决方案
您可以使用purrr::map
和变体:
library(tidyverse)
Y <- mtcars %>% select(hp, disp)
map(set_names(3:6), ~kmeans(Y, .x)) %>%
map(broom::augment, Y) %>%
imap(~mutate(.x, num_clust = .y)) %>%
bind_rows() %>%
ggplot(aes(hp, disp)) +
geom_point(aes(color = .cluster)) +
stat_ellipse(aes(x=hp,y=disp,fill=factor(.cluster)),
geom="polygon", level=0.95, alpha=0.2) +
facet_wrap(~num_clust)
推荐阅读
- sql - 当行不存在时 SQL 返回预定义的字符串
- sql - 选择过去 100 年不存在记录的行
- php - Laravel Eloquent: hasManyThrough 多对多关系
- .net - 引发 OnPropertyChanged 后 UI 未更新
- c# - WPF:使用对象以编程方式引发 SelectionChangedEvent
- node.js - 安装 NPM 包失败,出现不相关的包错误
- delphi - 通过 Indy 验证任何 URL 的 SSL 根证书
- differential-equations - 使用 Matlab BVP4C 进行时间演化
- linux - 在 Yocto 中如何进行成像和恢复
- qt - 使用来自 QtLocation 的卫星视图作为 3D 场景中的地面纹理