2

Possible Duplicate:
write.csv() a list of unequally sized data.frames

I have a data frame called patients3 with 100 rows and 129 columns, which I write out to a .csv file using write.csv.

My client would like several lines appended to the beginning of this file. The exact contents of some of the lines depend on variables in the same data, and some do not. Each row has a different number of columns. The first row is simple,

FILEFORMATID 1000

I tried this code

line1 <- data.frame(cbind("FILEFORMATID", "1000"))


######### OUTPUT MANAGEMENT 4: WRITING FILES
write.csv(line1, paste("c:/personal/consults/ElwinWu/output", filenum, ".csv"))
write.csv(patients3, paste("c:/personal/consults/ElwinWu/output", filenum, ".csv"), quote = FALSE, append = T)

but got a warning

Warning message: In write.csv(patients3, paste("c:/personal/consults/ElwinWu/output", : attempt to set 'append' ignored

and, indeed, the earlier file was overwritten.

Can this be done within R?

Thanks

Community
  • 1
  • 1
Peter Flom
  • 2,008
  • 4
  • 22
  • 35
  • 2
    Pretty nearly the same question as [this](http://stackoverflow.com/questions/7351049/write-csv-a-list-of-unequally-sized-data-frames)? – joran Sep 09 '11 at 17:51
  • 2
    Answers in this question may be of some help: http://stackoverflow.com/questions/5500522/how-to-prepend-to-a-file-add-at-the-top – Roman Luštrik Sep 09 '11 at 18:03

1 Answers1

4

There are a few ways I can think of. One would be to create a single data frame and then write it out to a CSV. This is kind of a pain. The other way(s) would be to either write out the body of the data into a file and then prepend your header info to that file or, conversely, write out the header info then append the csv body to that file.

I'd take an approach of creating the headers first and then appending the csv second. To get the ability to append, however, you have to switch from the write.csv() to write.table()

Here's an example:

header <- "my first line"
body <- data.frame(a=rnorm(10), b=rnorm(10))
write.table(header, file="/tmp/myfile.txt", row.names=F, col.names=F, quote=F)
write.table(body, file="/tmp/myfile.txt", row.names=F, col.names=F, append=T, sep=",")

and, as you would expect, the resulting file looks like this:

$ cat myfile.txt 
my first line
1.23874432711773,-2.2589990017634
0.231896206292307,1.17882048865978
-0.314437880898758,0.902090923407546
1.4997037042092,0.626724662264575
0.0695743692981956,0.250950969342156
1.33403372000003,0.552648907461989
0.182234972030415,0.950754253582309
-0.0960762881273546,-0.714485753494804
-0.850532439053779,1.89170555264949
0.269472111643762,1.39531731667127
JD Long
  • 59,675
  • 58
  • 202
  • 294