[R] Export the result k-means cluster to CSV file

S Ellison S.Ellison at LGCGroup.com
Thu Mar 24 18:49:49 CET 2016

> Hello Everyone : i have  done the clustering  process by k-means cluster, then i
> try to save[Export ] the groups of clustering, to txt, or CSV files , how i can do
> that 

Depends what you want.
You can save the whole object for reloading using save()

The cluster members can be written to text files using write(cl$cluster, file="<some file name>").
The whole thing can be written, without names, using something like

lapply(cl, write, file="cluster.txt", append=TRUE)
#Using cl from the first example in ?kmeans

If you need sensible breaks and names in the file, you'll have to roll your own alternative write routines. For example

Write <- function(NN, x, filename="cluster.txt", ...) {
	write(NN, filename, append=TRUE, ...)
	write(x[[NN]], filename, append=TRUE, ...)
	cat("\n", file=filename, append=TRUE, ...)

lapply(names(cl), Write, x=cl, filename="myclust.txt")

(Ignore the NULLs returned)

Anything more structured than that and you'll have to write a write.kmeans replacement for write that structures the results as you need them later.

S Ellison

This email and any attachments are confidential. Any use, copying or
disclosure other than by the intended recipient is unauthorised. If 
you have received this message in error, please notify the sender 
immediately via +44(0)20 8943 7000 or notify postmaster at lgcgroup.com 
and delete this message and any copies from your computer and network. 
LGC Limited. Registered in England 2991879. 
Registered office: Queens Road, Teddington, Middlesex, TW11 0LY, UK

More information about the R-help mailing list