YannickN.fr
YannickN.fr

Reputation: 360

How to quote just a column with write.csv/table in R?

I have this result with my data after a write.csv in R:

Last_Name,Sales,Country,Quarter
Smith,$16,753.00 ,UK,Qtr 3
Johnson,$14,808.00 ,USA,Qtr 4
Williams,$10,644.00 ,UK,Qtr 2

and I want this result (which is the original format of my data):

Last_Name,Sales,Country,Quarter
Smith,"$16,753.00 ",UK,Qtr 3
Johnson,"$14,808.00 ",USA,Qtr 4
Williams,"$10,644.00 ",UK,Qtr 2

because obviously I have some problems with amounts!

but I don't want :

"Last_Name","Sales","Country","Quarter"
"Smith,"$16,753.00 ","UK","Qtr 3"
"Johnson","$14,808.00 ","USA","Qtr 4"
"Williams","$10,644.00 ","UK","Qtr 2"

Any ideas?

Upvotes: 2

Views: 1846

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522406

Try quoting the sales column by itself:

df$Sales <- paste0("\"", df$Sales, "\"")

Then call write.csv without quotes. Or, you may specify which columns you want quoted in your call to write.csv:

write.csv(file="out.csv", df, quote=c(2))

Upvotes: 2

MichaelChirico
MichaelChirico

Reputation: 34753

This is the default behavior of data.table::fwrite, which only quotes columns as needed (in your case, to disambiguate the internal comma of the Sales field):

library(data.table)
fwrite(y)
# Last_Name,Sales,Country,Quarter
# Smith,"$16,753.00 ",UK,Qtr 3
# Johnson,"$14,808.00 ",USA,Qtr 4
# Williams,"$10,644.00 ",UK,Qtr 2

I'm just writing to stdout for convenience, of course you can specify an output file as the second argument (file). You can also control this behavior with the quote argument; "auto", works as follows (from ?fwrite):

When "auto", character fields, factor fields and column names will only be surrounded by double quotes when they need to be; i.e., when the field contains the separator sep, a line ending \n, the double quote itself or (when list columns are present) sep2[2] (see sep2 below).

As a bonus, of course, fwrite is way (can be upwards of 100x) faster than write.csv.

Upvotes: 2

Related Questions