Delimiters while writing csv files in R

谁都会走 提交于 2019-12-11 15:57:37

问题


How can I use |(pipe) as a delimiter while writing csv files in R?

When I try writing a data set into a file with write.csv with sep = "|", it ignores the separator and writes the file simply as a comma separated file.

Also write.csv2 also doesn't seem to cover the other variety of characters which could be used as a separator.

Is there a way to use other characters such as ^, $, ~, ¬ or |, as a delimiter while writing a csv file in R.

Thanks.


回答1:


You have to understand that .csv means "comma-separated value" https://en.wikipedia.org/wiki/Comma-separated_values.

If you want to export with a separator using that characters you need another function.

For example, using write.table, and you'll be able to load this file with R, Excel,....

write.table(data, "data.txt", sep = "|")
data_load <- read.table("data.txt", sep = "|")

Feel free to use any character as separator.

Or you could force this plain text to be .csv

write.table(data, "data.csv", sep = "|")
data_load <- read.csv("data.csv", sep = "|")



回答2:


This answer is just a variation of the one I gave for this question. They are similar, but I don't think the question itself is an exact duplicate, but they are both part of a bigger question (not yet asked).

In the help for write.table, it states:

write.csv and write.csv2 provide convenience wrappers for writing CSV files.

...

These wrappers are deliberately inflexible: they are designed to ensure that the correct conventions are used to write a valid file. Attempts to change append, col.names, sep, dec or qmethod are ignored, with a warning.

To set sep or another of these parameters you need to use write.table instead of write.csv.



来源:https://stackoverflow.com/questions/50269872/delimiters-while-writing-csv-files-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!