【问题标题】:Is there an R function that reads text files with \n as a (column) delimiter?是否有一个 R 函数可以读取带有 \n 作为(列)分隔符的文本文件?
【发布时间】:2021-04-12 14:24:06
【问题描述】:

问题

我正在尝试想出一种简洁/快速的方法来将由换行符 (\n) 分隔的文件读入多个列。

基本上在给定的输入文件中,输入文件中的多行应该成为输出中的单行,但是大多数文件读取函数会明智地将换行符解释为表示新行,因此它们最终会成为数据框单列。这是一个例子:

输入文件如下所示:

Header Info
2021-01-01
text
...
@
2021-01-02
text
...
@
...

... 表示输入文件中可能存在的多行,@ 表示输出数据帧中一行的真正结尾。所以在读取这个文件时,它应该变成这样的数据框(忽略标题):

X1 X2 ... Xn
2021-01-01 text ... ...
2021-01-02 text ... ...
... ... ... ...

我的尝试

我尝试过basedata.tablereadrvroom,它们都有两个输出之一,要么是具有单列的数据框,要么是向量。我想避免 for 循环,因此我当前的解决方案是使用 base::readLines() 将其读取为字符向量,然后手动添加一些“正确”的列分隔符(例如 ;),然后再次加入和拆分。

# Save the example data to use as input
writeLines(c("Header Info", "2021-01-01", "text", "@", "2021-01-02", "text", "@"), "input.txt")

input <- readLines("input.txt")
input <- paste(input[2:length(input)], collapse = ";") # Skip the header
input <- gsub(";@;*", replacement = "\n", x = input)
input <- strsplit(unlist(strsplit(input, "\n")), ";")
input <- do.call(rbind.data.frame, input)

# Clean up the example input
unlink("input.txt")

我上面的代码有效并给出了预期的结果,但肯定有更好的方法吗? 编辑:这是函数内部的,因此任何简化的部分(可能是较大部分)目的是提高速度。

提前致谢!

【问题讨论】:

  • 如果您正在寻找一种快速的方法来做到这一点,我建议在 unix 操作系统上使用 grepsed 之类的东西,将所有 \n 替换为一些分隔符,然后将 @ 替换为 \n .然后读入数据。否则,R 包 stringi 对于字符串操作非常快。也就是说,我不知道有什么包可以让你用换行符分割。
  • 为了替换你最后的步骤,大多数数据读取函数都将向量作为输入,即fread("hello,world\n1,2")readr::read_csv("hello,world\n1,2") 一样工作

标签: r data.table readr


【解决方案1】:

1) 读入数据,找到给出逻辑变量 at 的 @ 符号,然后创建一个分组变量 g,它对每个所需的行都有不同的值。最后使用带有 paste 的 tapply 将其重新加工成可以使用 read.table 读取的行并读取它。 (如果数据中有逗号,则使用其他分隔符。)

L <- readLines("input.txt")[-1]
at <- grepl("@", L)
g <- cumsum(at)
read.table(text = tapply(L[!at], g[!at], paste, collapse = ","), 
  sep = ",", col.names = cnames)

给出这个数据框:

          V1   V2
1 2021-01-01 text
2 2021-01-02 text

2) 另一种方法是通过删除 @ 符号并在其他行前面加上列名和冒号,将数据重新加工成 dcf 格式。然后使用 read.dcf。 cnames 是您要使用的列名的字符向量。

cnames <- c("Date", "Text")

L <- readLines("input.txt")[-1]
LL <- sub("@", "", paste0(c(paste0(cnames, ": "), ""), L))
DF <- as.data.frame(read.dcf(textConnection(LL)))
DF[] <- lapply(DF, type.convert, as.is = TRUE)
DF

给出这个数据框:

        Date Text
1 2021-01-01 text
2 2021-01-02 text

3) 这种方法只是将数据重新整形为矩阵,然后将其转换为数据框。请注意,(1) 将数字列转换为数字,而这一列只是将它们保留为字符。

L <- readLines("input.txt")[-1]
k <- grep("@", L)[1]
as.data.frame(matrix(L, ncol = k, byrow = TRUE))[, -k]
##           V1   V2
## 1 2021-01-01 text
## 2 2021-01-02 text

基准测试

这个问题没有提到速度作为考虑因素,但后来在评论中提到了它。根据以下基准中的数据,(1) 运行速度是问题中代码的两倍,(3) 运行速度快近 25 倍。

library(microbenchmark)

writeLines(c("Header Info", 
   rep(c("2021-01-01", "text", "@", "2021-01-02", "text", "@"), 10000)), 
   "input.txt")

library(microbenchmark)
writeLines(c("Header Info", rep(c("2021-01-01", "text", "@", "2021-01-02", "text", "@"), 10000)), "input.txt")

microbenchmark(times = 10,
ques = {
  input <- readLines("input.txt")
  input <- paste(input[2:length(input)], collapse = ";") # Skip the header
  input <- gsub(";@;*", replacement = "\n", x = input)
  input <- strsplit(unlist(strsplit(input, "\n")), ";")
  input <- do.call(rbind.data.frame, input)
},
ans1 = {
  L <- readLines("input.txt")[-1]
  at <- grepl("@", L)
  g <- cumsum(at)
  read.table(text = tapply(L[!at], g[!at], paste, collapse = ","), sep = ",")
},
ans3 = {
  L <- readLines("input.txt")[-1]
  k <- grep("@", L)[1]
  as.data.frame(matrix(L, ncol = k, byrow = TRUE))[, -k]
})
## Unit: milliseconds
##  expr     min      lq    mean  median      uq     max neval cld
##  ques 1146.62 1179.65 1188.74 1194.78 1200.11 1219.01    10   c
##  ans1  518.95  522.75  548.33  532.59  561.55  647.14    10  b 
##  ans3   50.47   51.19   51.68   51.69   52.25   52.52    10 a  

【讨论】:

  • 谢谢。选项 1 有效,但并不比我的解决方案快,选项 2 无效,因为列名可能事先未知(抱歉,可能应该在原始帖子中)。不过,我感谢您的努力!
  • 问题没有提到速度。重点是简化循环。
  • 嗯,第一行提到了整洁/快速,但公平点,它本来可以更明确。如果您有任何其他关于速度的建议,我很乐意听到。
  • 添加了第三种方法和基准。第三种方法的运行速度比使用基准测试中的数据的问题中的代码快近 25 倍。
  • 太好了,非常感谢!不过,我接受了您的回答,因为您的第三个解决方案既优雅又比我的解决方案快得多。
【解决方案2】:

您可以通过以下方式绕过一些字符串操作:

input <- readLines("input.txt")[-1] #Read in and remove header
ncol <- which(input=="@")[1]-1  #Number of columns of data
data.frame(matrix(input[input != "@"], ncol = ncol, byrow=TRUE)) #Convert to dataframe 
#          X1   X2
#1 2021-01-01 text
#2 2021-01-02 text

【讨论】:

  • 谢谢!这正是我一直在徘徊的地方,而且快了大约 4-6 倍。我将添加一些基准。
【解决方案3】:

此时,您可能会考虑全力以赴并使用适当的语法来解析它。我不知道情况到底有多大或有多复杂,但使用 pegr 可能看起来像这样:


input <-
"Header Info
2021-01-01
text
multiple lines
of
text
@
2021-01-02
text
more
lines of text
@
"

library(pegr)
peg <- new.parser(commonRules,action=TRUE) +
    c("HEADER   <- 'Header Info' EOL" , "{}"  ) + # Rule to match literal 'Header Info' and a \n, then discard
    c("TYPE     <- 'text' EOL"        , "{-}" ) + # Rule to match literal 'text', store paste and store as $TYPE
    c("DATE     <- (!EOL .)* EOL"     , "{-}" ) + # Rule to match any character leading up to a new line. Could improve to look for a date format
    c("EOS      <- '@' EOL"           , "{}"  ) + # Rule to match end of section, then discard
    c("BODY     <- (!EOS .)*"         , "{-}" ) + # Rule to match body of text, including newlines
    c("SECTION  <- DATE TYPE BODY EOS"        ) + # Combining rules to match each section
    c("DOCUMENT <- HEADER SECTION*"           )   # Combining more rules to match the endire document

res <- peg[["DOCUMENT"]](input))

final <- matrix( value(res), ncol=3, byrow=TRUE ) %>%
    as.data.frame %>%
    setnames( names(value(res))[1:3])

final

生产:

         DATE TYPE                       BODY
 1 2021-01-01 text multiple lines\nof\ntext\n
 2 2021-01-02 text      more\nlines of text\n

如果您不知道语法,可能会觉得很笨拙,但是一旦您知道了,它就是一个“一劳永逸”的解决方案。它将根据规范运行,直到规范不成立。您不必担心脆弱的预处理,并且很容易适应未来不断变化的格式。

【讨论】:

  • 感谢您的回答。我不知道这会起作用,因为每个 @ 符号之间的行数对于给定的文件是相同的,但对于不同的输入文件可能会有所不同。不过,我很感谢您的意见
  • 它不关心有多少行文本,它只是解析到@字符
  • 正如您在上面的示例输入中看到的那样,一个部分有 3 行文本,另一个有 2 行文本。这并不重要,它只是搜索标记每个部分结束的“@”。
  • 谢谢,我得再调查一下
  • np,对于这种情况,我认为它可能矫枉过正,这取决于您需要对格式有多灵活,将来是否会改变等。 declarative ,这意味着一旦您熟悉语法,就很容易使用它。它可能不是最快的解决方案,但它提供了我所说的其他优势。它有多种语言版本,但它们或多或少都基于此:en.wikipedia.org/wiki/Parsing_expression_grammar
【解决方案4】:

还有tidyverse方式:

library(tidyr)
library(readr)
library(stringr)

max_columns <- 5

d <- {
  readr::read_file("file.txt") %>% 
  stringr::str_remove("^Header Info\n") %>% 
  tibble::enframe(name = NULL) %>% 
  separate_rows(value, sep = "@\n")  %>% 
  separate("value", into = paste0("X", 1:max_columns) , sep = "\n") 
}

在名为 file.txt 的文件中使用您的示例输入,d 看起来像:

# A tibble: 3 x 5
  X1         X2    X3    X4    X5   
  <chr>      <chr> <chr> <chr> <chr>
1 2021-01-01 text  ...   ""    NA   
2 2021-01-02 text  ...   ""    NA   
3 ...        NA    NA     NA   NA   
Warning message:
Expected 5 pieces. Missing pieces filled with `NA` in 3 rows [1, 2, 3]. 

请注意,警告只是为了确保您知道自己得到了 NA,如果 @ 之间的行数不同,这是不可避免的

【讨论】:

    【解决方案5】:

    我正在使用类似于Sirius 提供的数据进行演示。您也可以执行类似的操作以在结果数据框中拥有可变数量的列

    example <- "Header Info
    2021-01-01
    text
    multiple lines
    of
    text
    @
    2021-01-02
    text
    more
    lines of text
    @"
    library(tidyverse)
    
    example %>% as.data.frame() %>% setNames('dummy') %>%
      separate_rows(dummy, sep = '\\n') %>%
      filter(row_number() !=1) %>%
      group_by(rowid = rev(cumsum(rev(dummy == '@')))) %>%
      filter(dummy != '@') %>%
      mutate(name = paste0('X', row_number())) %>%
      pivot_wider(id_cols = rowid, names_from = name, values_from = dummy)
    #> # A tibble: 2 x 6
    #> # Groups:   rowid [2]
    #>   rowid X1         X2    X3             X4            X5   
    #>   <int> <chr>      <chr> <chr>          <chr>         <chr>
    #> 1     2 2021-01-01 text  multiple lines of            text 
    #> 2     1 2021-01-02 text  more           lines of text <NA>
    

    reprex package (v2.0.0) 于 2021-05-30 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2019-04-01
      • 1970-01-01
      相关资源
      最近更新 更多