Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write csv with two header lines?

Tags:

r

Can I export a data.frame to csv with two header lines, one line for the column names, and one line for the comments on the column names? For instance,

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 hint appreciated, also on alternatives to comment()!

like image 367
Karsten W. Avatar asked Feb 28 '11 16:02

Karsten W.


People also ask

Can a CSV file have multiple headers?

A CSV file can have multiple rows after the header row. Each row corresponds to an artifact that will be created.

How do I specify a header in CSV?

If your CSV file doesn't have headers, you can add them by simply creating a new first line in the text file and typing in your headers.

What is header line in CSV?

A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file.


2 Answers

If you want to preserve the numeric nature of the data, I don't think we can do it with an easy one-liner (the answer provided by @Chase changes the data type to character), but we can do it via a few manipulations that write names(d) and the two comments out to the file first and then uses write.table() to write the csv data lines, appending to the file we just wrote the names and comments to:

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
  a b
1 1 5
2 3 6
3 4 7
> write.csv3(d, file = "myfile.csv")

Which produces the following file:

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

compared to that produced by @Chase's Answer:

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

Between the two, you should have sufficient options.

like image 176
Gavin Simpson Avatar answered Sep 27 '22 18:09

Gavin Simpson


Would rbind()ing your comments to the top of your data.frame be an option before writing out? If you make a new object, you won't impact the structure or class of the 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")
like image 25
Chase Avatar answered Sep 27 '22 17:09

Chase