In a dataset, I have a few columns where the contents are names or addresses that may contain commas. For example, "Einstein, Albert" or "Devon St., 8". When trying to write a csv file using the write.csv command, R splits the strings and creates additional columns in some cases:
write.csv(data, "output.csv", rownames=F, quote=F)
Name Address NumberP Phone Einstein Albert Rue 8 8 00000000000 David Rosa Ocho 9 11 0000000000000
How can I bypass this issue?
The quote=F
parameter you passed in your call to write.csv
might tip it off for you. You told R to not quote the fields, which means that a column with literal commas will therefore appear in the output with literal commas. Changing to quote=TRUE
should get around this problem:
write.csv(data, "output.csv", rownames=FALSE, quote=TRUE)
Note that now your output will have each field escaped in double quotes, at least those which need it to be unambiguous. But most place where you would import this CSV file know how to handle this (e.g. Excel).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With