Add header to file created by "write.csv"

I am trying to automate some export of data, and I would like to add a header for each file, for example, "please quote Bob and Jane 2008" ... or even a few lines of specific instructions depending on the context.

I looked at the documentation of write.csv and write.table, but I do not see such a function.

What is the easiest way to achieve this?

+5
source share
1 answer

Here are two possible approaches: a solution for EDIT using compounds is more flexible and efficient.


Use write.table(...,append = T)andcat

  • Use append=Tin a call write.tablewith cata header earlier

wrapped in its own function ....

write.table_with_header <- function(x, file, header, ...){
  cat(header, '\n',  file = file)
  write.table(x, file, append = T, ...)
}

, append write.csv,

write.table_with_header(x,file,header,sep=',')

csv.


( @flodel, )

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 suggestion)
  if(!missing(header)) writeLines(header,con=datafile)
# write the file using the defined function and required addition arguments  
  f(x, datafile,...)
}

, write.csv write.table , ( @flodel ) . !

+14

All Articles