【问题标题】:Passing a variable to the width argument in read.fwf将变量传递给 read.fwf 中的宽度参数
【发布时间】:2020-09-27 10:01:13
【问题描述】:

我要解决的问题是我需要读取多个固定宽度的文件,每个文件的列宽可能不同。所以我想遍历一些文件并将其与正确的模式匹配,并在正确的位置读取数据。

我还没有找到将架构文件传递给 read.fwf 或 read_fwf 的方法,并且不想进行硬编码,因此我将列长度拉到了下面的可变简化代码中

widths <- "10,5,5,10"
widths <- noquote(widths)

read_fwf("file.txt", fwf_widths(c(widths)))

但得到如下错误

Error in abs(widths) : non-numeric argument to mathematical function Error in abs(widths) : non-numeric argument to mathematical function

是否可以通过这种方式传递变量,或者它总是将其作为文本读取。

【问题讨论】:

  • 也许:read.fwf("file.txt", c(10,5,5,10))
  • 或者如果 widths 作为字符给出:read.fwf("file.txt", as.integer(strsplit(widths, ",")[[1L]]))
  • @GKi 最后一个看起来有效,谢谢。

标签: r


【解决方案1】:

@GKi 的回答完成了这项工作。

read.fwf("file.txt", as.integer(strsplit(widths, ",")[[1L]]))

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2021-07-28
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多