Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple tables in from a single text file?

Tags:

r

text-files

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 for those titles.

Thanks for the help.

like image 263
James Avatar asked Aug 31 '11 22:08

James


2 Answers

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.

like image 139
Travis Nelson Avatar answered Oct 06 '22 00:10

Travis Nelson


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.

like image 33
Omar Wagih Avatar answered Oct 06 '22 01:10

Omar Wagih