这里有两种可能的方法 - EDIT using connections 下的解决方案更加灵活和高效。
使用write.table(...,append = T) 和cat
- 在对
write.table 的调用中使用append=T,之前有cat 标头
封装在自己的函数中......
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's 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 在 cmets 中指出的那样)
只会打开和关闭文件一次,并自动附加。所以效率更高!