使用“write.csv”创建的文件如何添加标题

7

我想要自动化一些数据导出工作,并且我希望在每个文件的头部添加一些内容,例如“请引用Bob和Jane 2008年的资料”或根据具体情况添加几行特定的指示。

我已经查看了write.csv和write.table文档,但是没有看到任何这样的功能。

那么,怎样最轻松地实现这个功能呢?


你可以使用 writeLines 添加标题,然后使用选项 append=TRUEwrite.csv 写入数据。 - DrDom
4
对于 write.csvappend 被忽略并自动设置为 F,请改用 write.table, sep = ',' - mnel
1个回答

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

使用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, ...)
}

注意,在write.csv调用中,将忽略append,因此您只需要调用 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.csvwrite.table或任何功能,并使用文件连接,该连接(如@ flodel在评论中指出的那样)仅会打开和关闭一次文件,并自动追加。因此,它更有效率!

2
考虑使用 fileclose 打开和关闭文件连接。否则,您将打开和关闭文件两次,这有点低效。通过已打开的连接,您始终在进行追加操作,因此不需要 append = TRUE,而可以使用 write.csv - flodel
为了使这个函数完全灵活,可以添加一行代码,以便即使没有标题也能正常工作。类似于 if(!missing(header)) writelines(headder,con=datafile)。然后你可以将它命名为 "mywrite" :-) 而不是 "write.with.header.maybe"。 - Carl Witthoft
第二个函数(my.write)按原样适用于我。第一个函数(write.table_with_header)需要“rownames = F”; 考虑将“edit”移到顶部,以防有人像我这样懒得向下滚动。 - N Brouwer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接