I created the following function to generate a plot of 2D PC projection of features while showing kmeans clusters:
plot_kmeans_pc <- function(feature_matrix, k, pc) {
matrix_name <- deparse(substitute(feature_matrix)) # name of input variable
pclusters <- kmeans(feature_matrix, k, nstart=100, iter.max=100)
groups <- pclusters$cluster
projected <- predict(pc, newdata=feature_matrix)[,1:2] # project data onto two principle comps
projected_df <- cbind(as.data.frame(projected),
cluster=as.factor(groups))
p <- ggplot(projected_df, aes(x = PC1, y = PC2, colour = groups)) +
geom_point() +
ggtitle(matrix_name)
return(p)
}
Function runs and returns normally. However, when I try to plot the returned plot I get an error, e.g.
> p1clust2 <- plot_kmeans_pc(data, 2, data_pc)
> p1clust2
Error in eval(expr, envir, enclos) : object 'groups' not found