R read.csv如何忽略回车? [英] R read.csv how to ignore carriage return?
问题描述
我需要阅读一个文本文件(制表符分隔),该文件在某些字段中包含回车符.
I need to read a text file (tab-separated) that has some carriage returns inside some fields.
如果我使用read.table,它会给我一个错误:
If I use read.table, it gives me an error:
line 6257 did not have 20 elements
如果我使用read.csv,它不会出现错误,但会在该位置创建一个新行,将下一个字段放在新行的第一个字段中.
If I use read.csv, it doesn't give an error, but creates a new line in that place, putting the next fields in the first fields of the new line.
如何避免这种情况?我无法更改文件本身(脚本将在其他位置运行).另外,损坏的字符串没有引号(文件中没有字符串).一种选择是将回车符读为单个空格或\ n,但如何?
How can I avoid this? I can't alter the file itself (the script is to be run elsewhere). Also the broken strings don't have quotation marks (no strings in the file have). One option would be to read the carriage return as a single space, or as \n, but how?
推荐答案
使用read.table代替read.csv,并将allowEscapes设置为TRUE.
Use read.table instead of read.csv and set allowEscapes to TRUE.
read.table("your/path",sep=",",allowEscapes=TRUE)
我测试了以下内容:
- 在excel中编写一个csv文件
csv文件的内容:
1,df,3,"4
"
df,"df
",3,a
结果:
V1 V2 V3 V4
1 1 df 3 4 \n
2 df df\n 3 a
这篇关于R read.csv如何忽略回车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!