PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 30, 2022

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

 August 30, 2022     csv, r     No comments   

Issue

I simply want to export my matrix into a csv file but some columns contain comma in their values. 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)".

Any thoughts on how to escape this and wrap "PLAZA HOTEL(CHAMPAGNE BAR,ROSE CLUB, PALM COURT, EMPLOYEE CAFETERIA)" together?

Thanks!


Solution

Use the qMethod and quote parameters to write.csv:

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


Answered By - hd1
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing