我有一个包含空格分隔字符的文本文件:
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
函数问题?
答案 0 :(得分:4)
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