有没有办法附加文件并将列名保留在 data.table 中?

Is there a way to append file and keep the columns names in data.table?

我想在 data.table 的顶部添加一行,同时我将它导出到 csv!

library(data.table)
cat("Source Date: 01/01/2020\n", file = "dt.csv")
dt <- data.table(a = 1:5)
fwrite(dt, "dt.csv", append =TRUE)

我不确定我是否正确理解了你的问题。但是在fwrite函数中加入col.names=TRUE:

library(data.table)
cat("Source Date: 01/01/2020\n", file = "dt.csv")
dt = data.table(a = 1:5)
fwrite(dt, "dt.csv", append = TRUE, col.names = TRUE)

如果您想阅读此文件,您需要跳过第一个“源日期...”行:

> fread("dt.csv", skip = 1, header=TRUE)
   a
1: 1
2: 2
3: 3
4: 4
5: 5