【问题标题】:Read multiple tables in from a single text file?从单个文本文件中读取多个表?
【发布时间】:2011-11-08 00:19:48
【问题描述】:

我有一个包含多个表格的 .txt 文件。有没有办法将这些中的每一个读入自己的数据框中?每个“表”前面都有一行,上面有它的标题,所以我可以搜索这些标题。

感谢您的帮助。

【问题讨论】:

    标签: r text-files


    【解决方案1】:

    简单的谷歌搜索返回了这个。 非常适合我。

    > x <- readLines(textConnection("1
    + Pietje
    + I1 I2 Value
    + 1  1  0.11
    + 1  2  0.12
    + 2  1  0.21
    +
    + 2
    + Jantje
    + I1 I2 I3 Value
    + 1  1  1  0.111
    + 3  3  3  0.333"))
    > closeAllConnections()
    > start <- grep("^[[:digit:]]+$", x)
    > mark <- vector('integer', length(x))
    > mark[start] <- 1
    > # determine limits of each table
    > mark <- cumsum(mark)
    > # split the data for reading
    > df <- lapply(split(x, mark), function(.data){
    +     .input <- read.table(textConnection(.data), skip=2, header=TRUE)
    +     attr(.input, 'name') <- .data[2]  # save the name
    +     .input
    + })
    > # rename the list
    > names(df) <- sapply(df, attr, 'name')
    > df
    $Pietje
      I1 I2 Value
    1  1  1  0.11
    2  1  2  0.12
    3  2  1  0.21
    
    $Jantje
      I1 I2 I3 Value
    1  1  1  1 0.111
    2  3  3  3 0.333
    

    Source

    【讨论】:

      【解决方案2】:

      您将要读取整个文件,然后将其解析为表格标题或空行。如果/当您更改 txt 文件中的表时,我会将标题设置为您设置的 var 并将其放在脚本的顶部,以便您轻松更改。

      【讨论】:

      • 好的,谢谢。所以我用lines &lt;- scan(inFile, what="character", sep="\n") 阅读了整篇文章。第一个表在第一行有标题,在第一行有标题,在第一列有 row.names。表格的数据部分总是 32 行。我如何抢到第一张桌子?
      • 我会使用 readLines (因为我知道我会得到什么),然后使用段作为输入:例如。 read.table(textConnection(lines[2:33])
      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2015-11-08
      • 2013-08-18
      • 2015-08-05
      • 1970-01-01
      • 2012-10-06
      • 2010-12-13
      • 2015-08-11
      相关资源
      最近更新 更多