writeCSV: Write CSV files with quotes same as MS Excel 2013 or newer

Description Usage Arguments Details Value Author(s) Examples

View source: R/utils.R

Description

R'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.

Usage

1

Arguments

x

a data frame

file

character string for file name

row.names

Default FALSE for row.names

Details

This works by manually inserting quotation marks where necessary and turning FALSE R's own method to insert quotation marks.

Value

the return from write.table, using revised quotes

Author(s)

Paul Johnson

Examples

1
2
3
4
5
6
7
8
9
set.seed(234)
x1 <- data.frame(x1 = c("a", "b,c", "b", "The \"Washington, DC\""),
      x2 = rnorm(4), stringsAsFactors = FALSE)
x1
fn <- tempfile(pattern = "testcsv", fileext = ".csv")
writeCSV(x1, file = fn)
readLines(fn)
x2 <- read.table(fn, sep = ",", header = TRUE, stringsAsFactors = FALSE)
all.equal(x1,x2)

Example output

                    x1         x2
1                    a  0.6607697
2                  b,c -2.0529830
3                    b -1.4992061
4 The "Washington, DC"  1.4712331
[1] "x1,x2"                                         
[2] "a,0.660769736644892"                           
[3] "\"b,c\",-2.052983003941"                       
[4] "b,-1.49920605110092"                           
[5] "\"The \"\"Washington, DC\"\"\",1.4712331168047"
[1] TRUE

kutils documentation built on April 30, 2020, 1:05 a.m.