将标题添加到"write.csv"创建的文件

Abe*_*Abe 7 r header

我想自动执行某些数据导出,我想添加一个头的每个文件,如"请举Bob和2008年简" ......或根据上下文的具体说明,甚至几行.

我查看了write.csv和write.table文档,但没有看到任何此类功能.

实现这一目标的最简单方法是什么?

mne*_*nel 17

这里有两种可能的方法 - 使用连接EDIT下的解决方案更加灵活和高效.


使用write.table(...,append = T)cat

  • 使用append=T一个呼叫中write.table,有cat头有以前

包裹在自己的功能....

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

请注意,appendwrite.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's suggestion)
  if(!missing(header)) writeLines(header,con=datafile)
# write the file using the defined function and required addition arguments  
  f(x, datafile,...)
}
Run Code Online (Sandbox Code Playgroud)

请注意,此版本允许您使用write.csv或使用write.table任何函数并使用文件连接(如@flodel在注释中指出的那样)仅打开和关闭文件一次,并自动追加.因此效率更高!

  • 考虑使用`file`和`close`来打开和关闭文件连接.否则你打开和关闭文件两次,效率有点低.有了打开的连接,你总是追加,所以你不需要`append = TRUE`,你可以使用`write.csv`. (2认同)