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.
write.table(...,append = T)
and cat
append=T
within a call to write.table
, having cat
the header there previouslywrapped in its own function....
write.table_with_header <- function(x, file, header, ...){
cat(header, '\n', file = file)
write.table(x, file, append = T, ...)
}
Note that append
is ignored in a write.csv
call, so you simply need to call
write.table_with_header(x,file,header,sep=',')
and that will result in a csv file.
(Thanks to @flodel whose suggestion is this)
my.write <- function(x, file, header, f = write.csv, ...){
# create and open the file connection
datafile <- file(file, open = 'wt')
# close on exit
on.exit(close(datafile))
# if a header is defined, write it to the file (@CarlWitthoft's suggestion)
if(!missing(header)) writeLines(header,con=datafile)
# write the file using the defined function and required addition arguments
f(x, datafile,...)
}
Note that this version allows you to use write.csv
or write.table
or 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With