用R语言对2011年我国城镇居民人均消费情况进行聚类分析的代码
时间: 2023-07-24 22:35:37 浏览: 132
您好,以下是用R语言对2011年我国城镇居民人均消费情况进行聚类分析的代码,希望能够帮到您:
```R
# 导入数据
data <- read.csv("data.csv", header = TRUE, sep = ",")
# 将数据集中的省份名称作为行名
rownames(data) <- data[, 1]
data <- data[, -1]
# 标准化数据
data_norm <- scale(data, center = TRUE, scale = TRUE)
# 聚类分析
set.seed(123)
km <- kmeans(data_norm, 3) # 将数据分成3类
# 绘制聚类结果图
plot(data_norm, col = km$cluster, main = "K-means Clustering Results")
# 将聚类结果添加到原数据集
data_cluster <- data
data_cluster$cluster <- km$cluster
# 输出每一类的省份名称
cat("Cluster 1:", rownames(data_cluster[data_cluster$cluster == 1, ]), "\n")
cat("Cluster 2:", rownames(data_cluster[data_cluster$cluster == 2, ]), "\n")
cat("Cluster 3:", rownames(data_cluster[data_cluster$cluster == 3, ]), "\n")
```
其中,数据集需要自行准备,格式为.csv文件,包含各个省份的人均消费数据。在这里,我将数据集中的省份名称作为行名,因此需要在读入数据后将第一列作为行名并将其从数据集中删除。接着,对数据进行标准化处理,然后使用kmeans函数将数据分为3类,并使用plot函数将聚类结果可视化。最后,输出每一类的省份名称。
阅读全文
相关推荐















