简体   繁体   English

如何使用 R 将数据帧/矩阵写入 CSV,但值中有逗号

[英]How to write the dataframe/matrix into CSV using R but with commas in values

I simply want to export my matrix into a csv file but some columns contain comma in their values.我只是想将我的矩阵导出到 csv 文件中,但有些列的值中包含逗号。 I also tried to replace the commas with other symbols, such as "|".but it still does not work.我还尝试将逗号替换为其他符号,例如“|”。但它仍然不起作用。

For example my text looks like this例如我的文字看起来像这样

"41305348","PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)","1","768","5 AVENUE","10019","2127593000","03","2012-10-25 00:00:00","U","10F","27","B","2012-10-25 00:00:00","2013-02-15 01:01:09.020000000"
"41305395","DUMPLING HOUSE","1","118 A","ELDRIDGE STREET","10002","2126258008","20","2013-01-10 00:00:00","D","10F","13","A","2013-01-10 00:00:00","2013-02-15 01:01:09.020000000"

webextract.raw=readLines(mytext)
webextract.split2=sapply(webextract.raw,function(x)strsplit(x,"[^[:alpha:]],[^ ]"))
t=sapply(c(1:14),function(x)sapply(webextract.split2,function(y)y[x]))
write.table(t,"t.csv")

If I use write.table directly, the first record will be separated into more columns than the second one as there are commas in "PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)" .如果我直接使用write.table ,第一条记录将被分成比第二条更多的列,因为"PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)"中有逗号。

Any thoughts on how to escape this and wrap "PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)" together?关于如何摆脱这种情况并将"PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)"在一起的任何想法?

Thanks!谢谢!

使用 qMethod 和 quote 参数来write.csv

write.csv(my.text, stdout(), qmethod='escape', quote=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM