Karina
Karina

Reputation: 15

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?

Upvotes: 0

Views: 1200

Answers (2)

IRTFM
IRTFM

Reputation: 263362

lukeA's answer looks more direct, but this would allow you to convert a comma-containing column into one that has actual quotes:

> dat[] <- lapply(dat, function(x) if (is.character(x) & any(grepl("[,]",x)) ){ paste0("\"", x, "\"")} else{x} )
> dat
  col1 col2 col3  col4
1    1    1    A "A,B"
2    2    2    B "a,b"
3    3    3    c "a,b"

Those should appear in output from write.csv with quote=FALSE.

Upvotes: 0

lukeA
lukeA

Reputation: 54237

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.

Upvotes: 1

Related Questions