【发布时间】:2011-11-08 00:19:48
【问题描述】:
我有一个包含多个表格的 .txt 文件。有没有办法将这些中的每一个读入自己的数据框中?每个“表”前面都有一行,上面有它的标题,所以我可以搜索这些标题。
感谢您的帮助。
【问题讨论】:
标签: r text-files
我有一个包含多个表格的 .txt 文件。有没有办法将这些中的每一个读入自己的数据框中?每个“表”前面都有一行,上面有它的标题,所以我可以搜索这些标题。
感谢您的帮助。
【问题讨论】:
标签: r text-files
简单的谷歌搜索返回了这个。 非常适合我。
> 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
【讨论】:
您将要读取整个文件,然后将其解析为表格标题或空行。如果/当您更改 txt 文件中的表时,我会将标题设置为您设置的 var 并将其放在脚本的顶部,以便您轻松更改。
【讨论】:
lines <- scan(inFile, what="character", sep="\n") 阅读了整篇文章。第一个表在第一行有标题,在第一行有标题,在第一列有 row.names。表格的数据部分总是 32 行。我如何抢到第一张桌子?
read.table(textConnection(lines[2:33])