'fread'与领先/尾随空格不兼容?

时间:2014-08-18 18:32:16

标签: r whitespace data.table fread

我正在尝试读取一个文本文件,其中的列由空格分隔,在R中。我尝试使用data.table,因为read.csv需要很长时间才能阅读。但是,第一列有前导空格,我在fread()中收到以下错误 "在测试标题行的格式后未​​正确定位。 CH =' '"

数据格式类似于

    45 36 46  
    45 67 35

有没有办法可以使用fread()读取而无需重新格式化纺织品?

3 个答案:

答案 0 :(得分:1)

# This example reproduces the error
library(data.table)
in.df <- data.frame(A=c(" a1"," b2"," c3"," d4"), B=c(11,22,33,44),
                    stringsAsFactors=FALSE)
write.table(in.df, file="testing.dat", quote=FALSE, row.names=FALSE, col.names=FALSE)
test.df <- fread(input="testing.dat", sep=" ", header=FALSE, stringsAsFactors=FALSE,
                 verbose=TRUE)

# I can't find a solution in ?fread

答案 1 :(得分:0)

如果您使用的是Linux,请尝试fread("sed 's/^[[:blank:]]*//' testing.dat")sed命令将删除testing.dat中每行的前导空格。

答案 2 :(得分:0)

这是使用readLines的解决方案,但我不确定速度。

require(data.table)

setwd("~")

in.df <- data.table(A = c(" a1"," b2"," c3"," d4"),
                    B = c(11,22,33,44))
in.df

write.table(in.df, file="testing.dat", quote = F,
            row.names = F, col.names = F)

dat <- paste(sub("^\\s+", "", readLines("testing.dat")), collapse = "\n")
dat

test.df <- fread(dat, stringsAsFactors = F)
test.df