R 读取固定宽度格式,其中宽度从列标题推断

R 读取固定宽度格式,其中宽度从列标题推断,r,dataframe,read.table,R,Dataframe,Read.table,我有一个相当奇怪的文件格式,我需要阅读。它有空格分隔的列,但列宽必须从标题推断 此外,还有一些伪行必须忽略,包括空白行和非空白行 数据的表示形式: The first line contains some text that is not important, and shoud be ignored. The second line also. In addition, the third and fifth lines are blank. col1 co

我有一个相当奇怪的文件格式,我需要阅读。它有空格分隔的列,但列宽必须从标题推断

此外,还有一些伪行必须忽略,包括空白行和非空白行

数据的表示形式:

The first line contains some text that is not important, and shoud be ignored.
The second line also.  In addition, the third and fifth lines are blank.

       col1          col2    col3  col4     col5

  ab   cd e      132399.4     101     0 17:25:24  Ignore anything past the last named column
       blah        773411      25    10 17:25:25  Ignore this too
这里,第一列col1包含从行首到文本字符串col1结尾的字符位置的文本。第二列col2包含从col1中1后面的下一个字符到文本字符串col2结尾的文本。等等

实际上,有17列而不是5列,但这不应该改变代码

我正在寻找一个包含以下内容的数据框:

         col1     col2 col3 col4      col5
1   ab   cd e 132399.4  101    0  17:25:24
2        blah 773411.0   25   10  17:25:25
这是一个相当不雅观的方法:

read.tt <- function(file) {
  con <- base::file(file, 'r')
  readLines(con, n=3);
  header <- readLines(con, n=1)
  close(con)
  endpoints <- c(0L, gregexpr('[^ ]( |$)', header)[[1]])
  widths <- diff(endpoints)
  names <- sapply(seq_along(widths),
                  function(i) substr(header, endpoints[i]+1, endpoints[i]+widths[i]))
  names <- sub('^ *', '', names)
  body <- read.fwf(file, widths, skip=5)
  names(body) <- names
  body
}
一定有更好的办法


要忽略的行是这个难题的一小部分。我将接受一个解决方案,该解决方案可以处理已从文件中删除的内容,但当然更喜欢不需要预处理的内容。

如果您知道标题行,可以使用以下方法获得宽度

x
## [1] "         col1     col2 col3 col4      col5"

nchar(unlist(regmatches(x, gregexpr("\\s+\\S+", x))))
## [1] 13  9  5  5 10

看起来像是sed或awk在外面的工作R@geektrader对于删除伪行,是的,但是推断列宽这一更重要的部分呢?我认为你基本上有正确的方法。一次读取一行以到达标题行,解析该行以获得字段边界的列号,然后使用这些边界调用Read.fwf。这可能比diffc0L、gregexpr'[^]|$',header[[1]]更优雅,但我不能假设我知道标题行。我应该从文件中读出来。@MatthewLundberg你需要在文本中有某种你想忽略的模式。前n行,或示例中以此开头的行。con