Write csv with two header lines?

Is it possible to export the data.frame file to csv with two header lines, one line for column names and one line for comments on column names? For example,

d <- data.frame(a=c(1,3,4), b=c(5,6,7)) comment(d$a) <- "MWh" comment(d$b) <- "%" write.csv(d, "myfile.csv", ???) 

Any hints appreciated, as well as alternatives to comment ()!

+8
source share
3 answers

If you want to preserve the numerical nature of the data, I don’t think we can do this with a simple one-line (the answer provided by @Chase changes the data type to a character), but we can do this through a few manipulations that write names(d) , and two comments go to the file first, and then use write.table() to write csv data lines, adding to the file that we just wrote the names and comments:

 write.csv3 <- function(d, file) { opts <- options(useFancyQuotes = FALSE) on.exit(options(opts)) h1 <- paste(dQuote(c("", names(d))), collapse = ",") h2 <- paste(dQuote(c("", comment(d$a), comment(d$b))), collapse = ",") writeLines(paste(h1, h2, sep = "\n"), file) write.table(d, file, sep = ",", append = TRUE, col.names = FALSE) } 

Here is an example:

 > d <- data.frame(a=c(1,3,4), b=c(5,6,7)) > comment(d$a) <- "MWh" > comment(d$b) <- "%" > d ab 1 1 5 2 3 6 3 4 7 > write.csv3(d, file = "myfile.csv") 

Which creates the following file:

 $ cat myfile.csv "","a","b" "","MWh","%" "1",1,5 "2",3,6 "3",4,7 

compared to the results obtained with @Chase Answer:

 $ cat output.csv "","a","b" "1","MHh","%" "2","1","5" "3","3","6" "4","4","7" 

Between the two, you should have enough options.

+11
source

Can rbind() add your comments to the top of your data.frame before writing? If you create a new object, you will not affect the structure or class of existing columns.

 d <- data.frame(a=c(1,3,4), b=c(5,6,7)) output <- rbind(c("MHh", "%"), d) write.csv(output, "output.csv") 
+5
source

I have some small modifications to the excellent answer from @Gavin Simpson.

  • It is not obvious in the OP whether string names are required. I deleted them and changed the header offset

  • using fwrite() from the data.table package instead of write.table() reduces processing time to 1/10 compared to the base function.

 library(data.table) write.csv3 <- function(data, file, header) { opts <- options(useFancyQuotes = FALSE) on.exit(options(opts)) h1 <- paste(dQuote(c(header)), collapse = ",") h2 <- paste(dQuote(c(names(data))), collapse = ",") writeLines(paste(h1, h2, sep = "\n"), file) fwrite(data, file, sep = ",", append = TRUE, col.names = FALSE, row.names = FALSE) } 
+2
source

All Articles