[R] write.csv

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Mon Jul 30 23:24:16 CEST 2007


On 29-Jul-07 17:41:58, Dong GUO ¹ù¶« wrote:
> Hi,
> 
> I want to save an array(say, array[6,7,8]) write a cvs file.
> How can I do that??? can I write in one file?
> 
> if I could not write in one file, i want to use a loop to save
> in different files (in the array[6,7,8], should be 8 csv files),
> such as the filename structure should be:
> file ="filename" +str(i)+"." +"csv"
> 
> Many thanks.

The following (illustrated on a smaller array) may help:

A<-array((1:60),dim=c(3,4,5))
D<-dim(A)

write.table(t(dim(A)),file="A.csv",sep=",",
            quote=FALSE,row.names=FALSE,col.names=FALSE)

Z<-as.vector(A)
write.table(t(Z),file="A.csv",append=TRUE,sep=",",
            quote=FALSE,row.names=FALSE,col.names=FALSE)

Then the file A.csv contains two rows:

3,4,5
1,2,3,4,5,6,7,8,9,10,11,12, ... ,55,56,57,58,59,60

of which the first gives the dimension, the second the
data for the array.

You can then reconstruct another array, say B, as:

dimB<-scan(file="A.csv",sep=",",nlines=1)
dataB<-scan(file="A.csv",sep=",",skip=1,nlines=1)
B<-array(dataB,dimB)

That's a hard way to do things, perhaps, but since you said
you wanted the array as a CSV file, this is one way to do that.

Since a CSV text file is essentially a two-dimensional object
(fields in rows, by rows), to store a higher-dimensional object
in such a format you have to include the "meta-data" about the
structure -- in this case the list of dimensions.

Note, however, that, although it is a CSV file,

read.csv("A.csv",header=FALSE)

will not work nicely, since it will give you two rows of equal
length, the first one padded out with (in this case 57) NAs,
which you will then have to clean up; which you can do, but by
the time you've done it you might as well have done it the above
way!

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 30-Jul-07                                       Time: 22:24:12
------------------------------ XFMail ------------------------------



More information about the R-help mailing list