Search code examples
routputdouble-quotes

how to conditional remove double quotes in write.csv in R


I have data with both numeric and character values and the delimiter is a comma. however in some character values, there is comma as well. when I output as CSV file, I don't want to double quotes all my columns, both numeric and character columns, but only those have a comma.

data is like this:

col1 col2 col3 col4 ....
1    1    A    A,B ...
2    2    B    a,b ...
3    3    c    a,b ...

the output I want in CSV file should be like this:

col1 col2 col3 col4 ....
1    1    A    "A,B" ...
2    2    B    "a,b" ...
3    3    c    "a,b" ...

the code for write.csv(data,path, quote=T/F) can control all columns and rows instead of a specific cell. so does the code write.table(data,path, qmethod="double"/"escape")

I can only quote one column by defined like this:

write.csv(data,path, quote=2)

But I do want to quote only a few cells when they have a comma in it. Does anyone have an idea?


Solution

  • I think you can use write_csv from the readr package:

    df <- read.table(header=T, text='col1 col2 col3 col4
    1    1    A    "AB"
    2    2    B    "a,b"
    3    3    c    "a,b"')
    readr::write_csv(df, tf <- tempfile(fileext = ".csv"))
    file.show(tf)
    # col1,col2,col3,col4
    # 1,1,A,AB
    # 2,2,B,"a,b"
    # 3,3,c,"a,b"
    

    From ?readr::write_csv:

    Values are only quoted if needed: if they contain a comma, quote or newline.