Search code examples
rcluster-analysis

R exporting Kmeans clustering results into excel


i've run my kmeans test from an excel data source and now want to get he results out in excel. I've tried the following code but all i get is a blank worksheet. I'm relatively new to R so i imagine its something simple that I'm missing - please help!

set.seed(123)
kmeansresults<-kmeans(df[,7], 5, iter.max = 50, nstart = 100)
x<-kmeansresults$clusters
write.csv(x, "clustering results.csv")

Solution

  • Try the following:

    data("USArrests")
    m <- scale(USArrests)
    
    set.seed(123)
    km_res <- kmeans(m, 4, nstart=25)
    x <- km_res$cluster
    
    write.csv(x, "/Users/user/Desktop/foo.csv")
    

    I guess your problem was not writing a CSV file but calling km_res$clusters that should be km_res$cluster. In R you can access the structure of an object as str(km_res) to see what is "inside". There is no slot clusters but cluster.