我怎样才能得到fread()
设置""
到 NA
对于包括字符变量在内的所有变量?
我正在导入一个 .csv 文件,其中缺失值为空字符串( ""
;无空格)。我要 ""
被解释为缺失值 NA
并尝试 `na.strings = ""但没有成功:
data <- fread("file.csv", na.strings = "")
unique(data$character_variable)
# [1] "abc" "def" ""
另一方面,当我使用read.csv
时与 na.strings = ""
,""
变成 NA
s,即使对于字符变量也是如此。这就是我想要的结果。
data <- read.csv("file.csv", na.strings = "")
unique(data$character_variable)
# [1] "abc" "def" NA
版本
- R版本3.6.1(2019-07-05)
- data.table_1.12.8
最佳答案
好吧,如果你的 csv 文件看起来像这样,你就不能这样做
a,b
x,y
"",1
请注意,""
内的任何内容都被视为字符串文字,因为 ""
是转义字符。从这个意义上说,csv 文件中的 ,"",
仅表示空字符串,而不是缺失值(即 ,,
)。我认为这是一个保持一致性的好功能。 fread
文档的 na.strings
部分也写到了这一点:
A character vector of strings which are to be interpreted as
NA
values. By default,",,"
for columns of all types, including typecharacter
is read asNA
for consistency.,"",
is unambiguous and read as an empty string. To read,NA,
asNA
, setna.strings="NA"
. To read,,
as blank string""
, setna.strings=NULL
. When they occur in the file, the strings inna.strings
should not appear quoted since that is how the string literal,"NA",
is distinguished from,NA,
, for example, whenna.strings="NA"
.
另一方面,您可能会注意到,如果文件看起来像这样
a,b
1,y
"",1
,那么空字符串将被转换为NA
。但是,我认为这不是一个错误,因为这种行为可能是解析器类型强制的结果。在同一文档的详细信息
部分中,您可以看到
The lowest type for each column is chosen from the ordered list:
logical
,integer
,integer64
,double
,character
.
因此列 a
首先被读取为字符列,然后转换为整数列。空字符串仍按原样读取,但在第二步中强制转换为 NA_integer_
。
关于r - fread: na.strings 中的空字符串 ("") 不会被解释为 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64798564/