为什么fread会在data.table中插入回车符(\r)?

5
我正在使用Windows 10电脑上的data.table::fread从.csv文件中读取数据。通过read.csv,数据可以正确读入;然而,当我使用fread来读取数据时,结果数据表中每一行的最后一列都以\r结尾,这可能表示回车符。这会导致数字字段被赋予字符数据类型。(一个以字符文字4.53\r表示的行终止单元格,而不是数值文字4.53。)
为什么会发生这个错误?是否有一种直接通过fread函数调用解决此问题的方法?
更新:
当使用verbose=TRUE参数时,我得到以下结果:
Input contains no \n. Taking this to be a filename to open
File opened, filesize is 0.000001 GB.
Memory mapping ... ok
Detected eol as \n only (no \r afterwards), the UNIX and Mac standard.
Positioned on line 1 after skip or autostart
This line is the autostart and not blank so searching up for the last non-blank ... line 1
Detecting sep ... ','
Detected 7 columns. Longest stretch was from line 1 to line 13
Starting data input on line 1 (either column names or first row of data). First 10 characters: subjectNum
All the fields on line 1 are character fields. Treating as the column names.
Count of eol: 13 (including 1 at the end)
Count of sep: 72
nrow = MIN( nsep [72] / ncol [7] -1, neol [13] - nblank [1] ) = 12
Type codes (   first 5 rows): 1131414
Type codes: 1131414 (after applying colClasses and integer64)
Type codes: 1131414 (after applying drop or select (if supplied)
Allocating 7 column slots (7 - 0 dropped)
Read 12 rows. Exactly what was estimated and allocated up front
   0.000s (  0%) Memory map (rerun may be quicker)
   0.001s ( 33%) sep and header detection
   0.000s (  0%) Count rows (wc -l)
   0.002s ( 67%) Column type detection (first, middle and last 5 rows)
   0.000s (  0%) Allocation of 12x7 result (xMB) in RAM
   0.000s (  0%) Reading data
   0.000s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.000s (  0%) Coercing data already read in type bumps (if any)
   0.000s (  0%) Changing na.strings to NA
   0.003s        Total

你可以尝试创建一个可重现的例子,比如 fread("a\n1\r\n2\r\n")?在这种情况下,行尾标识符不一致,导致了你所看到的行为。 - Frank
这确实会导致 R 中的错误。当我在 Notepad++ 中读取文件时,该文件在第一行仅有 LF,在随后的行上则为 CR LF(\r\n)。请随意提交答案,以便我可以接受您的答案。 - Bob
你知道这在 .csv 文件中是否是常见情况吗? - Bob
1个回答

6
如果你有一个文件看起来像这样:x="a\n1\r\n2\r\n",那么fread(x)会给出如下结果:
     a
1: 1\r
2: 2\r

出现这种情况是因为行末标识在不同的行之间不一致。

我听说过其他人也遇到了这个问题,但我不确定它来自哪里或是否有比“修复”文件更好的解决方法,可能需要使用命令行工具。


我记得在邮件列表或Github上看到有人遇到过这个问题,但是找不到链接了。 - Frank
1
当我使用Python创建数据时,在Windows中使用\n硬编码标题时,我遇到了这个问题。Python os.linesep - user3226167

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接