0

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
recipriversexclusion
  • 13,448
  • 6
  • 34
  • 45
  • 5
    I think that `projected_df` doesn't have a column called `groups`. I don't think this is related to the function, if you tried to print (plot) the graph from inside the function it would fail as well. Maybe it's what you called `cluster`? – joran May 02 '18 at 20:40
  • Maybe instead of `cbind(...,cluster = ...)` you can do `cbind(...,groups = ...)`? I think Joran is right, it doesn't look like there is a `groups` column in your data. Also, it helps us debug if you include a snippet of your data. – Mike H. May 02 '18 at 20:48
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 02 '18 at 20:50
  • @joran's comment was correct, I thought it was some sort of local variable issue but I had the `ggplot` statement wrong. I changed it to `ggplot(projected_df, aes(x=PC1, y=PC2)) +geom_point(aes(color=cluster))+ggtitle(matrix_name)` and it works. Thanks for the help! – recipriversexclusion May 02 '18 at 21:02

0 Answers0