Gimelist
Gimelist

Reputation: 823

How to add arbitrary lines of text before write.csv() output in R?

minimal reproducible example

I have this code:

df <- data.frame(foo = 1:5, bar = 5:1)

bla <- "some text"

write.csv(df, "foobar.csv")

I would like the final foobar.csv to look like this:

some text

"","foo","bar"
"1",1,5
"2",2,4
"3",3,3
"4",4,2
"5",5,1


wider context

This is part of a Shiny app where I have this bit in the server function:

  output$dlcsv <- downloadHandler(
    filename = function() {
      paste0(format(Sys.time(), "%Y%M%e%H%M%S"), ".csv")
    },
    content = function(file) {
      write.csv(datareactive(), file)
    }
  )

output$dlcsv is a download button, and datareactive() is a data frame that I export to a csv named after today's date and time. I would like to add some lines to the text file before the data itself. So, the solution to the above question needs to work in this context.

Upvotes: 1

Views: 223

Answers (1)

duckmayr
duckmayr

Reputation: 16920

You can simply use cat() for bla, then switch to write.table() from write.csv() in order to be able to set append = TRUE:

df <- data.frame(foo = 1:5, bar = 5:1)

bla <- "some text"

cat(bla, "\n\n", file = "foobar.csv")

write.table(df, "foobar.csv", sep = ",", append = TRUE)

Resulting foobar.csv:

some text 

"foo","bar"
"1",1,5
"2",2,4
"3",3,3
"4",4,2
"5",5,1

Upvotes: 5

Related Questions