fread和read.table根据R中的same()给出不同的输出

时间:2016-07-24 19:56:10

标签: r fread read.table

我有一个包含空格分隔字符的文本文件:

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

当我知道identical()a包含相同数据,具有相同类别且相同{{1}时,为什么这两个读数的b结果不同}}?问题是fread还是str函数问题?

1 个答案:

答案 0 :(得分:4)

tl; dr 使用as.is阻止read.table将字符串转换为因子,或stringsAsFactors=TRUEfread中启用相同的行为。使用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