Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add header to file created by "write.csv"

Tags:

r

header

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?

like image 831
Abe Avatar asked Sep 12 '12 04:09

Abe


1 Answers

Here are two possible approaches - the solution under EDIT using connections is more flexible and efficient.


Using write.table(...,append = T) and cat

  • Use append=T within a call to write.table, having cat the header there previously

wrapped 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.


EDIT

using connections

(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!

like image 195
mnel Avatar answered Sep 30 '22 13:09

mnel