如何在 R 中只用 write.csv/table 引用一列?

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

write.csv in R:

之后,我的数据得到了这个结果
Last_Name,Sales,Country,Quarter
Smith,,753.00 ,UK,Qtr 3
Johnson,,808.00 ,USA,Qtr 4
Williams,,644.00 ,UK,Qtr 2

想要这个结果(这是我数据的原始格式):

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

因为显然我在数量上有一些问题!

但我不想 :

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

有什么想法吗?

尝试单独引用销售栏:

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

然后不带引号调用 write.csv。或者,您可以指定要在调用 write.csv:

时引用的列
write.csv(file="out.csv", df, quote=c(2))

这是 data.table::fwrite 的默认行为,它只根据需要引用列(在您的情况下,是为了消除 Sales 字段的内部逗号的歧义):

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

为了方便写给stdout,当然你可以指定一个输出文件作为第二个参数(file)。您还可以使用 quote 参数控制此行为; "auto",工作方式如下(来自?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).

作为奖励,当然,fwriteway (can be upwards of 100x) faster than write.csv