【问题标题】:add header to file created by "write.csv"将标题添加到由“write.csv”创建的文件中
【发布时间】:2012-09-13 06:42:25
【问题描述】:

我正在尝试自动化一些数据导出,并且我想在每个文件中添加一个标题,例如“请引用 Bob 和 Jane 2008”……甚至根据上下文添加几行具体说明。

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

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

【问题讨论】:

  • 您可以使用writeLines 添加标题,并使用write.csv 和选项append=TRUE 来写入您的数据。
  • append 被忽略并自动设置为F 用于write.csv,请改用write.table, sep = ','

标签: r header


【解决方案1】:

这里有两种可能的方法 - 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, ...)
}

请注意,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,...)
}

请注意,此版本允许您使用 write.csvwrite.table 或任何函数并使用文件连接 (正如@flodel 在 cmets 中指出的那样) 只会打开和关闭文件一次,并自动附加。所以效率更高!

【讨论】:

  • 考虑使用fileclose 打开和关闭文件连接。否则,您将两次打开和关闭文件,这有点低效。使用打开的连接,你总是在追加,所以你不需要append = TRUE,你可以使用write.csv
  • 为了使它成为一个完全灵活的函数,可以添加一行,这样即使没有标题也可以工作。像if(!missing(header)) writelines(headder,con=datafile) 这样的东西。然后你可以将它命名为“mywrite” :-) 而不是“write.with.header.maybe”
  • 第二个函数 (my.write) 按原样为我工作。第一个函数(write.table_with_header)需要“rownames = F”;考虑将“编辑”移到顶部,以防有人像我一样懒惰并且不向下滚动
猜你喜欢
  • 2014-12-26
  • 2019-04-05
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多