r - fread: na.strings 中的空字符串 ("") 不会被解释为 NA

标签 r data.table na fread read.table

我怎样才能得到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 type character is read as NA for consistency. ,"", is unambiguous and read as an empty string. To read ,NA, as NA, set na.strings="NA". To read ,, as blank string "", set na.strings=NULL. When they occur in the file, the strings in na.strings should not appear quoted since that is how the string literal ,"NA", is distinguished from ,NA,, for example, when na.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/

相关文章:

r - 使用 R 数据表计算累计日期的罢工率

r - 如何使用 Rtsne 包保留用户 ID

r - 在由 rgl package plot3d 建立的球体上有名字

R:按两个因素之一的值重新排序 geom_bar(stat = "identity",position=position_dodge())

r - 确定 NA 部分的开始和结束条款

r - 在 as.numeric() 中避免 NA

r - 如果矩阵包含任何NA,如何返回TRUE?

r - 试图将 R 环境中的所有内容保存到磁盘

linux - 错误 : could not find function install_github for R version 2. 15.2

r - 准确理解何时 data.table 是对另一个 data.table 的引用(而不是其副本)