writeCSV.RdR's write.csv inserts quotes around all elements in a character vector (if quote = TRUE). In contrast, MS Excel CSV export no longer inserts quotation marks on all elements in character variables, except when the cells include commas or quotation marks. This function generates CSV files that are, so far as we know, exactly the same "quoted style" as MS Excel CSV export files.
writeCSV(x, file, row.names = FALSE)the return from write.table, using revised quotes
This works by manually inserting quotation marks where necessary and turning FALSE R's own method to insert quotation marks.
set.seed(234)
x1 <- data.frame(x1 = c("a", "b,c", "b", "The \"Washington, DC\""),
x2 = rnorm(4), stringsAsFactors = FALSE)
x1
#> x1 x2
#> 1 a 0.6607697
#> 2 b,c -2.0529830
#> 3 b -1.4992061
#> 4 The "Washington, DC" 1.4712331
fn <- tempfile(pattern = "testcsv", fileext = ".csv")
writeCSV(x1, file = fn)
readLines(fn)
#> [1] "x1,x2"
#> [2] "a,0.660769736644892"
#> [3] "\"b,c\",-2.052983003941"
#> [4] "b,-1.49920605110092"
#> [5] "\"The \"\"Washington, DC\"\"\",1.4712331168047"
x2 <- read.table(fn, sep = ",", header = TRUE, stringsAsFactors = FALSE)
all.equal(x1,x2)
#> [1] TRUE