【问题标题】:'fread' not compatible with leading/trailing whitespace?'fread' 与前导/尾随空格不兼容?
【发布时间】:2014-10-11 18:02:36
【问题描述】:

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

数据格式类似,

    45 36 46  
    45 67 35

有没有什么方法可以在不重新格式化纺织品的情况下使用 fread() 读取?

【问题讨论】:

  • 是否有标题行?你能给出文件的前几行吗?
  • 不,没有标题行。

标签: r whitespace data.table fread


【解决方案1】:

这是使用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

【讨论】:

    【解决方案2】:

    如果你在 linux 下,试试fread("sed 's/^[[:blank:]]*//' testing.dat")sed 命令将删除testing.dat 中每一行的前导空格。

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 2023-03-30
      • 1970-01-01
      • 2018-01-25
      • 2012-02-28
      • 2017-03-16
      相关资源
      最近更新 更多