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.