fread 和 read.table 根据 R 中的 identical() 给出不同的输出
fread and read.table giving dissimilar outputs according to identical() in R
我有一个包含 space 个分隔字符的文本文件说:
a b c d e
我正在使用两种不同的方式阅读这个 .txt
文件,然后我比较两种阅读方式如下:
a <- fread("C:/Users/user/Desktop/New Text Document.txt",header=FALSE,data.table=FALSE)
b <- read.table("C:/Users/user/Desktop/New Text Document.txt")
> identical(a,b)
[1] FALSE
当我知道 a
和 b
包含相同的数据,具有相同的 class 时,为什么这两个读数的 identical()
的结果不同, 同样 str
?是fread的问题还是identical
函数的问题?
tl;dr 使用 as.is
来防止 read.table
将字符串转换为因子,或者 stringsAsFactors=TRUE
在 fread
。使用 str
来解决这个问题。
writeLines("a b c d e",con="tmpabc.txt")
str(A <- read.table("tmpabc.txt",header=FALSE))
'data.frame': 1 obs. of 5 variables:
$ V1: Factor w/ 1 level "a": 1
$ V2: Factor w/ 1 level "b": 1
$ V3: Factor w/ 1 level "c": 1
$ V4: Factor w/ 1 level "d": 1
$ V5: Factor w/ 1 level "e": 1
str(B <- data.table::fread("tmpabc.txt",header=FALSE,data.table=FALSE))
'data.frame': 1 obs. of 5 variables:
$ V1: chr "a"
$ V2: chr "b"
$ V3: chr "c"
$ V4: chr "d"
$ V5: chr "e"
C <- read.table("tmpabc.txt",header=FALSE,as.is=TRUE)
identical(B,C) ## TRUE
我有一个包含 space 个分隔字符的文本文件说:
a b c d e
我正在使用两种不同的方式阅读这个 .txt
文件,然后我比较两种阅读方式如下:
a <- fread("C:/Users/user/Desktop/New Text Document.txt",header=FALSE,data.table=FALSE)
b <- read.table("C:/Users/user/Desktop/New Text Document.txt")
> identical(a,b)
[1] FALSE
当我知道 a
和 b
包含相同的数据,具有相同的 class 时,为什么这两个读数的 identical()
的结果不同, 同样 str
?是fread的问题还是identical
函数的问题?
tl;dr 使用 as.is
来防止 read.table
将字符串转换为因子,或者 stringsAsFactors=TRUE
在 fread
。使用 str
来解决这个问题。
writeLines("a b c d e",con="tmpabc.txt")
str(A <- read.table("tmpabc.txt",header=FALSE))
'data.frame': 1 obs. of 5 variables:
$ V1: Factor w/ 1 level "a": 1
$ V2: Factor w/ 1 level "b": 1
$ V3: Factor w/ 1 level "c": 1
$ V4: Factor w/ 1 level "d": 1
$ V5: Factor w/ 1 level "e": 1
str(B <- data.table::fread("tmpabc.txt",header=FALSE,data.table=FALSE))
'data.frame': 1 obs. of 5 variables:
$ V1: chr "a"
$ V2: chr "b"
$ V3: chr "c"
$ V4: chr "d"
$ V5: chr "e"
C <- read.table("tmpabc.txt",header=FALSE,as.is=TRUE)
identical(B,C) ## TRUE