Read multiple tables in from a single text file?
I have a single .txt file with a number of tables in it. Is there a way to read each of these into its own data frame? Each 'table' is preceded by a line with its title on it, so I can search fo开发者_开发知识库r those titles.
Thanks for the help.
You're going to want to read in the entire file, then parse it for your table headers or empty lines. I'd make the headers a var that you set and have it be at the top of the script for you to change easily if/when you make changes to the tables in your txt file.
Simple google search returned this. Worked perfectly for me.
> 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.
精彩评论