Exporting file in CSV gives junk rows using write.csv / write_csv


while exporting the file from R to CSV , i found some junk rows ,
when i saw the same file in R using View(file), it looks fine.

but in R studio , it looks fine.

i don't know whats the issue?

sometimes it works fine with write_excel_csv function form Readr Package.

I'm guessing you have line breaks ("\n) characters in some of your fields. This forces a new line in write.csv.

I believe you will need to make a decision about how to handle those. One option is to use something like gsub("\n", "\\n", variable) to add an extra backslash. I'm not sure what best practice would be.

Thanks for the suggestion.

I used apply function to replace all the "\n", to "\n" but it didn't work. finally i removed the problem records(in my case last field of the data set. it worked fine.

i am not sure if the line break function works on other characters including "\n.


Could you please turn this into a self-contained reprex (short for reproducible example)? It will help us help you if we can be sure we're all working with/looking at the same stuff.


If you've never heard of a reprex before, you might want to start by reading the tidyverse.org help page. The reprex dos and don'ts are also useful.

What to do if you run into clipboard problems

If you run into problems with access to your clipboard, you can specify an outfile for the reprex, and then copy and paste the contents into the forum.

reprex::reprex(input = "fruits_stringdist.R", outfile = "fruits_stringdist.md")

For pointers specific to the community site, check out the reprex FAQ.

1 Like