0

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!

Geekuna Matata
  • 1,349
  • 5
  • 19
  • 38

2 Answers2

2

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
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
  • Ahh, `writeLines`... that's what I needed. After further review, mine won't work. Very nice. – Rich Scriven Apr 05 '14 at 03:19
  • The poster's question actually made me remember the `append` argument :-) I keep forgetting many of the `write…` functions have that. There are times that comes in really handy. – hrbrmstr Apr 05 '14 at 03:21
  • Right. I tried `rev(append(...` with no luck. Is there a way to reverse `append`? It prints the same result no matter which order you have the arguments listed. – Rich Scriven Apr 05 '14 at 03:21
  • I don't think so ([ref](http://stackoverflow.com/questions/16128001/is-it-possible-to-append-to-the-first-line-of-an-exisiting-file)). At least I've not been able to find `base` or `stats` function that wraps the process. – hrbrmstr Apr 05 '14 at 03:34
  • I got something with `sink`. See answer. – Rich Scriven Apr 05 '14 at 03:45
1

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245