-3

I wrote the follow code to clustering data :

clusrer.data <- function(data,n) {
  miRNA.exp.cluster <- scale(t(miRNA.exp))
  k.means.fit <- kmeans(miRNA.exp.cluster,n)
  #i try to save the results of k-means cluster by this code : 
  k.means.fit <- as.data.frame(k.means.fit)
  write.csv(k.means.fit, file="k-meanReslut.csv")
  #x<-k.means.fit$clusters
  #write.csv(x, file="k-meanReslut.csv")
}

but I can not save the clusters to outside of (clusters) (8, 6, 7, 20, 18), I want to save each cluster separated (with columns and rows) in txt file or CSV.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
hisham
  • 1
  • 2
  • Please rethink about how you're asking. We don't have access to your data. Paint us a picture of what we're after and what the expected result should look like. – Roman Luštrik Mar 27 '16 at 11:55
  • This is not enough. Please see [this post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to provide an example. – Roman Luštrik Mar 27 '16 at 13:48
  • i have done the clustering by k-means , the result 5 Clusters. after Clustering . i want to save the each cluster in txt or CSV file . every Cluster should contain names of columns and names of rows and the data in cluster. – hisham Mar 27 '16 at 13:54
  • Perhaps I'm not making myself clear. Provide us with an example that will demonstrate your problem or at least provide enough information about the data that gives us a fighting chance of what is going on. Also, it's not entirely clear what the result is suppose to look like. Please show that, too. – Roman Luštrik Mar 27 '16 at 13:58
  • this is example by iris data , ########## http://www.rdatamining.com/examples/kmeans-clustering ############ after clustering i want to save the clusters in txt file or csv file, every Cluster should contain names of columns and names of rows and the data in cluster – hisham Mar 27 '16 at 14:43
  • Please revisit my comments and answer. Until you address these points, there's really no point in debating further. – Roman Luštrik Mar 27 '16 at 17:31

1 Answers1

0

Here is one approach of splitting the original dataset according to cluster and saving that chunk to a file. I added cluster assignment to the original dataset for easier visual check. Example is partly taken from ?kmeans. Feel free to adapt the way files are written, as well as the way file name is created.

x <- rbind(matrix(rnorm(100, sd = 0.3), ncol = 2),
           matrix(rnorm(100, mean = 1, sd = 0.3), ncol = 2))
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))

x <- cbind(x, cluster = cl$cluster)

by(x, INDICES = cl$cluster, FUN = function(sp) {
  write.table(sp, file = paste0("file", unique(sp$cluster), ".txt"),
              row.names = TRUE, col.names = TRUE)
})
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197