Geekuna Matata
Geekuna Matata

Reputation: 1439

How can I append a header to a CSV file I am writing out in R?

I am able to export a dataframe into CSV file but I need to append two lines of information before I do that. I don't write out the column names.

Trend data
110

Here, "Trend data" is just a text. And, 110 is the number of rows in the data frame I am writing out.

How can I append this information in the header of the csv file I am writing out in R?

Thanks!

Upvotes: 1

Views: 1795

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99391

You can also use write.table and sink. The sink function diverts R output to a specified file, appending it to what's already in the file, if desired.

> x <- data.frame(x = letters[1:5])

> write.table("Trend Data\n110", row.names = FALSE, 
              col.names = FALSE, quote = FALSE, file = "my.csv")
> sink("my.csv", append = TRUE)
> x
> sink()

> write.table(readLines("my.csv"), row.names = FALSE,
              col.names = FALSE, quote = FALSE)
Trend Data
110
  x
1 a
2 b
3 c
4 d
5 e

Upvotes: 2

hrbrmstr
hrbrmstr

Reputation: 78852

This ought to do it:

x <- 1:110

writeLines(c("Trend data","110"), "myfile.dat")
write.table(x, "myfile.dat", col.names=FALSE, row.names=FALSE, append=TRUE)

Looking at it from the Mac OS X terminal:

$ head myfile.dat
Trend data
110
1
2
3
4
5
6
7
8

Upvotes: 3

Related Questions