Can I add to the first line of an existing file?

I looked at several functions that can add text to an existing data file (.csv or .txt), for example write.table, write.lines or sink.

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

Given a data frame:

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 add a new data frame to the last row 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)

This is close to what I want. But I would really like the above line to be added to the first line of DF.csv (right under the heading) like this:

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, ( , ).

+5
1

:

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)
}
+5

All Articles