Home > database >  Added commented section to output CSV with write_csv()
Added commented section to output CSV with write_csv()

Time:05-20

Is it possible to added comments to an CSV file output with write_csv()? The function read_csv() has the option comment = "#" to skip commented rows.

Example

# file created on 2022-05-19 (this is a comment)
date,count
2022-04-19,45
2022-04-20,35
2022-04-21,47
2022-04-22,26
2022-04-23,13

Any other options to get to the same result?

CodePudding user response:

The comment line is not part of the specification RFC4180. However, one can do

library(readr)

file <- "data.csv"
data <- iris

write_lines("# foo", file)
data |> colnames() |> paste0(collapse = ",") |> write_lines(file, append = TRUE)
write_csv(data, file, append = TRUE)

resulting in a file starting with:

# foo
Sepal.Length,Sepal.Width,Petal.Length,Petal.Width,Species
5.1,3.5,1.4,0.2,setosa
4.9,3,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
5,3.6,1.4,0.2,setosa
5.4,3.9,1.7,0.4,setosa
  •  Tags:  
  • r
  • Related