在R中的循环中跳过数据文件中的所有行并将其包含在循环中

Skip over all lines in a data file before and including a regular string in a loop in R

我有一台仪器可以生成包含大量 header 信息的数据文件。我想一次读取多个文件并将它们 rbind 放在一起。为了成功阅读这些内容,我一直在使用以下循环并跳过处理 header 信息:

df <- c()
for (x in list.files(pattern="*.cnv", recursive=TRUE)) {
u <-read.table(x, skip=100)
      df <- rbind(df, u)
}

以下是要跳过 5 行的数据文件的示例:

# Header information
# Header information
# Header information
# Header information
# Header information
*END*
      0.571    26.6331     8.2733    103.145     0.0842  -0.000049  0.000e+00
      0.576    26.6316     8.2756    103.171     0.3601  -0.000049  0.000e+00
      0.574    26.6322     8.2744    103.157     0.3613  -0.000046  0.000e+00

问题是要跳过的行数是动态的,我想提出一个通用的解决方案。幸运的是,每个文件都以此结尾:

*END*

所以我的问题是,我怎样才能读入一个文件,上面的内容跳过所有行并包含 *END* 行?这可能会在 rbind 将它们组合在一起之前发生。

使用

逐行读取输入
all_content = readLines("input.txt")
>all_content
[1] "# Header information"                                                         
[2] "# Header information"                                                         
[3] "# Header information"                                                         
[4] "# Header information"                                                         
[5] "# Header information"                                                         
[6] "*END*"                                                                        
[7] "      0.571    26.6331     8.2733    103.145     0.0842  -0.000049  0.000e+00"
[8] "      0.576    26.6316     8.2756    103.171     0.3601  -0.000049  0.000e+00"
[9] "      0.574    26.6322     8.2744    103.157     0.3613  -0.000046  0.000e+00"

然后使用 grep 删除行,直到您点击 *END* 如下

skip = all_content[-c(1:grep("*END*",all_content))]

现在使用正常的 read.table 函数阅读

input <- read.table(textConnection(skip))
> input
     V1      V2     V3      V4     V5       V6 V7
1 0.571 26.6331 8.2733 103.145 0.0842 -4.9e-05  0
2 0.576 26.6316 8.2756 103.171 0.3601 -4.9e-05  0
3 0.574 26.6322 8.2744 103.157 0.3613 -4.6e-05  0

你得到了想要的结果。

更新

在你的循环中使用

for (x in list.files(pattern="*.cnv", recursive=TRUE)) {
   all_content <- readLines(x)
   skip = all_content[-c(1:grep("*END*",all_content))]
   input <- read.table(textConnection(skip))
   df <- rbind(df, input)
}

您可以在 data.table::fread()

中使用 skip 选项
library(data.table)
dT = fread("# Header information
  # Header information
  # Header information
  # Header information
  # Header information
  *END*
    0.571    26.6331     8.2733    103.145     0.0842  -0.000049  0.000e+00
  0.576    26.6316     8.2756    103.171     0.3601  -0.000049  0.000e+00
  0.574    26.6322     8.2744    103.157     0.3613  -0.000046  0.000e+00", 
  skip ="*END*")