mad-a
mad-a

Reputation: 173

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

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 :)

Upvotes: 3

Views: 3924

Answers (2)

Carolina Macovei
Carolina Macovei

Reputation: 1

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)

Upvotes: 0

Stanislas Morbieu
Stanislas Morbieu

Reputation: 1827

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)

Upvotes: 9

Related Questions