是否可以附加到现有文件的第一行? [英] Is it possible to append to the first line of an exisiting file?

查看:26
本文介绍了是否可以附加到现有文件的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了几个能够将文本添加到现有数据文件(.csv 或 .txt)的函数,例如 write.table、write.lines 或 sink.

I've looked at several of the functions that are able to add text to an existing data file (.csv or .txt) such as write.table, write.lines, or sink.

当 append 参数 =TRUE 时,新数据总是添加到文件的最后一行之后.是否可以将数据添加到第一行(标题下方)的现有文件中 - 即与追加相反?

When the append argument =TRUE, the new data is always added after the last existing line of the file. Is it possible to add data to an existing file on first line (below a header)- AKA opposite of append?

给定一个数据框:

DF <- as.data.frame(matrix(seq(20),nrow=5,ncol=4))
colnames(DF) <- c("A", "B", "C", "D")
write.table(DF, "DF.csv", row.names=FALSE, sep=",")

我可以像这样在最后一行附加一个新的数据框

I can append a new data frame to the last line like this

A <- 1
A <- data.frame(A)
A$B <- 1
A$C <- 1
A$D <- 1
write.table(A, "DF.csv", row.names=FALSE, sep=",", append=TRUE, col.names=FALSE)

这与我想要的很接近.但我真的很想将上面的行添加到 DF.csv 的第一行(标题正下方),就像这样

Which is close to what I want. But I would really like to have the above line to be added to the first line of the DF.csv (right below the header) like so

A   B   C   D
1   1   1   1
1   6   11  16
2   7   12  17
3   8   13  18
4   9   14  19
5   10  15  20

明确地说,我不希望在 R 中的数据框中添加一行.我希望在 R 环境之外的文件的开头添加一行.正如 append 可用于将数据添加到外部 .csv 文件的末尾一样,我希望将数据附加"到 .csv 文件的开头,以便我的最新数据始终出现在第一行(以避免滚动到长文件的末尾以查看最新数据).

To be clear, I'd not looking to add a row into a data frame within R. I am hoping to add a row to the beginning of a file outside of the R environment. Just as append can be used to add data to the end of an external .csv file, I am hoping to "append" data to the beginning of a .csv file, so that my latest data always comes up in the first row (to avoid scrolling through to the end of a long file to see the most current data).

推荐答案

编写自己的函数:

my.write.table <- function(df, filename, sep)
{
   ## read the existing content
   temp.df <- read.table(filename, sep)

   ## append in front
   df <- rbind(df, temp.df)

   ## write back the whole data frame
   write.table(df, filename, sep)
}

这篇关于是否可以附加到现有文件的第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆