我是R的新手,正在尝试根据行业对某些数据进行聚类。我了解到K-means无法处理因子和分类数据。我从我的数据集中删除了名为“行业”的因素 - 67个不同的观察结果,但是想要在模型完成后为每个观察分配一个标签。基本上,我希望我的最终结果看起来像样本美国犯罪数据集。非常感谢任何帮助。
代码:
library(tidyverse) # data manipulation
library(cluster) # clustering algorithms
library(factoextra) # clustering algorithms & visualization
library(ggplot2) ## used for plotting
library(gridExtra) ## used for plotting
library(robustbase)
###Read in dataset
df <- read.csv('my_data')
df2 <- scale(df)
### Subset of Data -- looking at percentage closed won and total opportunities
dat = df2[,c(1,3)]
# initial cluster split
k2 <- kmeans(dat, centers = 2, nstart = 25)
str(k2)
k2
fviz_cluster(k2, data = dat)
### Additional Plots
k3 <- kmeans(dat, centers = 3, nstart = 25)
k4 <- kmeans(dat, centers = 4, nstart = 25)
k5 <- kmeans(dat, centers = 5, nstart = 25)
# comparing plots
p1 <- fviz_cluster(k2, geom = "point", data = dat) + ggtitle("k = 2")
p2 <- fviz_cluster(k3, geom = "point", data = dat) + ggtitle("k = 3")
p3 <- fviz_cluster(k4, geom = "point", data = dat) + ggtitle("k = 4")
p4 <- fviz_cluster(k5, geom = "point", data = dat) + ggtitle("k = 5")
grid.arrange(p1, p2, p3, p4, nrow = 2)
## Computing gap statistics
set.seed(123)
gap_stat <- clusGap(df, FUN = kmeans, nstart = 25,
K.max = 10, B = 50)
## Visualization
fviz_gap_stat(gap_stat)
# Compute k-means clustering with k = 4
set.seed(123)
final <- kmeans(dat, 4, nstart = 25)
print(final)
## final visualization
fviz_cluster(final, data = dat)
答案 0 :(得分:1)
我认为您需要做的只是:
rownames(df) <- df$Industry
然后缩放和子集。行业名称将显示在群集图上,而不是行号上。