2011-08-31 80 views
8

我有一个单独的.txt文件,里面有许多表格。有没有办法将它们中的每一个读入它自己的数据框?每个“表”前面都有一个标题,所以我可以搜索这些标题。从单个文本文件中读取多个表?

感谢您的帮助。

回答

2

你将要读入整个文件,然后解析它为你的表头或空行。如果/当您对txt文件中的表进行更改时,我会将标题设置为您设置的一个变量,并将其置于脚本的顶部,以供您轻松更改。

+0

好的,谢谢。所以我用'lines < - scan(inFile,what =“character”,sep =“\ n”)''来读取整个事物。第一个表的第一行标题,第一行标题和第一列row.names。表中的数据部分总是32行。我如何抓住第一张桌子? – James

+2

我会用readLines(因为我知道我会得到什么),然后使用段作为输入:例如。函数read.table'(textConnection(行[2:33])' –

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