fviz_cluster() not accepting for k-medoid (PAM) results

核能气质少年 提交于 2021-02-10 20:24:59

问题


Trying to visualize k-medoid (PAM) cluster results with fviz_cluster(), however function isn't accepting them.

It states within ?fviz_clust "object argument = an object of class "partition" created by the functions pam(), clara() or fanny() in cluster package"

I've tried accessing the clustering vector through other means;

pam_gower_2$clustering
pam_gower_2[[3]]

but then I get a separate error:

Error: $ operator is invalid for atomic vectors"

The class of pam_gower_2 is partition? As the argument expects.

class(pam_gower_2)
> class(pam_gower_2)
[1] "pam"       "partition"

Here's the code I'm using:

df_gower <- df[, c(2:21)] 
df_gower <- df_gower[, c(1:4, 11:12, 14:15, 5:10, 16:20)] 

gower_dist <- daisy(df_gower, metric="gower", type=list(ordratio=c(2:4, 6), symm=c(7:8), asymm=c(5), logratio=c(13)))

gower_mat <- as.matrix(gower_dist)
tendency_gower <- get_clust_tendency(gower_mat, 100, graph=T)
tendency_gower$hopkins_stat

fviz_nbclust(gower_mat, pam, method="wss")
fviz_nbclust(gower_mat, pam, method="silhouette")

pam_gower_2 <- pam(gower_mat, k=2, diss=T)

# all of the above functions as expected

fviz_cluster(pam_gower_2, gower_mat)

above line produces the following error:

Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), :'data' must be of a vector type, was 'NULL'

Would greatly appreciate feedback/ fix, reasons as to why this doesn't work, or an alternative method for visualizing.

Thanks :)


回答1:


Here is the documentation of fviz_cluster:

data: the data that has been used for clustering. Required only when object is a class of kmeans or dbscan.

You therefore only need to pass the results of pam to fviz_cluster.

Here is a minimal example of fviz_cluster with pam:

library("factoextra")
library("cluster")

data("USArrests")
res <- pam(USArrests, 4)
fviz_cluster(res)

If you apply pam with a distance matrix, you have your error. A workaround is to set the data field of the result afterwards. Here is the modified example using a distance matrix (diss):

library("factoextra")
library("cluster")

data("USArrests")

diss = dist(USArrests)
res <- pam(diss, 4)

res$data = USArrests
fviz_cluster(res)



回答2:


I have solved this problem by adding row.names=1 when I load the dataset:

read.csv2("index.csv",header=T, sep=";", dec=",", row.names=1)


来源:https://stackoverflow.com/questions/58716614/fviz-cluster-not-accepting-for-k-medoid-pam-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!