从单个文本文件中读取多个表?

时间:2011-08-31 22:17:26

标签: r text-files

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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