【问题标题】:Read in specific, pattern-matched rows from a file从文件中读取特定的、模式匹配的行
【发布时间】:2012-04-29 17:53:31
【问题描述】:

我有一个制表符分隔的文件,其中包含多个表,每个表都以标题为标题,例如“Azuay\n”、“Bolivar\n”、“Cotopaxi\n”等,每个表由两个分隔换行符。在 R 中,我如何读取此文件并仅选择对应于例如的表(即指定的行) “Bolivar”,而忽略对应于“Cotopaxi”的下表和对应于“Azuay”的上表。

注意。我不想修改 R 之外的表格。

数据如下所示。该文件是制表符分隔的。

 Azuay
 region begin       stop
 1A     2017761     148749885
 1A     148863885   150111299
 1A     150329391   150346152
 1A     150432847   247191037


 Bolivar
 region begin           stop 
 2A     2785            242068364
 2A     736640          198339289


 Cotopaxi
 region begin           stop 
 4A     2282            9951846
 4A     11672561        11906166

【问题讨论】:

  • 能否附上典型的文件或示例数据?

标签: r data-processing


【解决方案1】:

这似乎可以完成工作:

read.entry.table <- function(file, entry) {

   lines <- readLines(file)

   table.entry <- lines == entry
   if (sum(table.entry) != 1) stop(paste(entry, "not found"))

   empty.lines <- which(lines == "")
   empty.lines <- c(empty.lines, length(lines) + 1L)

   table.start <- which(table.entry) + 1L
   table.end   <- empty.lines[which(empty.lines > table.start)[1]] - 1L

   return(read.table(textConnection(lines[seq(from = table.start,
                                              to   = table.end)]),
                     header = TRUE))
}

read.entry.table("test.txt", "Bolivar")
#   region  begin      stop
# 1     2A   2785 242068364
# 2     2A 736640 198339289

read.entry.table("test.txt", "Cotopaxi")
#   region    begin     stop
# 1     4A     2282  9951846
# 2     4A 11672561 11906166

【讨论】:

  • 太好了。此外,正如我在文件中发现的那样,在列的末尾有一个选项卡,所以额外的代码行(在返回 read.table 之前结果将是 lines[table.start] &lt;- sub("\t$","",lines[table.start])
  • 非常令人印象深刻
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多