I am trying to automate some data exporting, and I would like to add a header to each file such as “please cite Bob and Jane 2008” … or even a few lines of specific instructions depending on the context.
I have looked at the write.csv and write.table documentation, but do not see any such feature.
What is the easiest way to achieve this?
Here are two possible approaches – the solution under EDIT using connections is more flexible and efficient.
Using
write.table(...,append = T)andcatappend=Twithin a call towrite.table, havingcatthe header there previouslywrapped in its own function….
Note that
appendis ignored in awrite.csvcall, so you simply need to callwrite.table_with_header(x,file,header,sep=',')and that will result in a csv file.
EDIT
using connections
(Thanks to @flodel whose suggestion is this)
Note that this version allows you to use
write.csvorwrite.tableor any function and uses a file connection which(as @flodel points out in the comments)
will only open and close the file once, and automatically appends. Therefore it is more efficient!