问题描述
我已经完成并绘制了R markdown中的DBSCAN集群。
这是我目前的代码:
dbscan.8=fpc::dbscan(current.matrix,eps=2,MinPts=log(33359)) #list generated
fviz_cluster(dbscan.8,data=current.matrix,stand=FALSE,ellipse=FALSE,show.clust.cent=FALSE,geom="point",palette="jco",ggtheme=theme_classic()) # Plot the clusters
如何在原始数据帧(current.matrix)中添加一个新列,其中包含每一行所属的簇?所以看起来像这样:
谢谢!
解决方法
使用示例数据集:
library(factoextra)
library(fpc)
dat = data.frame(scale(iris[,-5]))
clus = dbscan(dat,1.5)
集群看起来像这样
viz = fviz_cluster(clus,data=dat,stand=FALSE,ellipse=FALSE,show.clust.cent=FALSE,geom="point",palette="jco")
print(viz)
集群信息已经存储在来自fviz_cluster的对象中:
head(viz$data)
name x y coord cluster
1 1 -2.257141 -0.4784238 5.323576 1
2 2 -2.074013 0.6718827 4.752956 1
3 3 -2.356335 0.3407664 5.668437 1
4 4 -2.291707 0.5953999 5.606421 1
5 5 -2.381863 -0.6446757 6.088877 1
6 6 -2.068701 -1.4842053 6.482388 1
集群也以dbscan
的形式存储在$clusters
对象下。因此,您可以这样做:
dat$cluster = viz$data$cluster
或:
dat$cluster = clus$cluster