Is it possible to read two tables from the same text file?

橙三吉。 提交于 2019-12-12 05:24:38

问题


For instance, if I have a text file (mytext.txt) with the following text:

Table1

    13  3   20  0   0   0   0
    3   10  0   0   0   6   0
    20  0   5   0   0   0   0
    0   0   0   7   20  0   0
    0   0   0   20  19  0   0
    0   0   0   0   0   8   0
    0   0   0   0   0   0   13  

Table2
0
2
10
-5
3
-10
-5

Can I retrieve both of them and get two tables?

So that if I print my data table1 I would get the first table and if I print my data table 2 I would get the second table.

I know that if mytext.txt only had one table I could do something like:

table1 <- read.table("mytext.txt")

回答1:


1) Assuming the input file is tables.txt, read the lines into Lines and let names.ix be the indexes of the lines containing the table names -- these lines are identified as beginning with a character that is not a minus or digit. Then create a grouping variable grp which identifies which table each line belongs to, split the lines into those groups and read each group of lines. This uses no packages and can handle any number of tables in the file.

Lines <- readLines("tables.txt")
names.ix <- grep("^[^-0-9]", Lines)
grp <- Lines[names.ix][ cumsum(seq_along(Lines) %in% names.ix) ]
Read <- function(x) read.table(text = x)
L <- lapply(split(Lines[-names.ix], grp[-names.ix]), Read)

giving:

> L
$Table1
  V1 V2 V3 V4 V5 V6 V7
1 13  3 20  0  0  0  0
2  3 10  0  0  0  6  0
3 20  0  5  0  0  0  0
4  0  0  0  7 20  0  0
5  0  0  0 20 19  0  0
6  0  0  0  0  0  8  0
7  0  0  0  0  0  0 13

$Table2
   V1
1   0
2   2
3  10
4  -5
5   3
6 -10
7  -5

2) By the way, if you only need the first table then this does it:

library(data.table)
fread("tables.txt")



回答2:


Not directly, but you can try read.mtable from my "SOfun" package, available only on GitHub.

The approach is similar to @G.Grothendieck's approach, but packaged into a function, so you can simply do:

read.mtable("tables.txt", chunkId = "Table", header = FALSE)
# $Table1
#   V1 V2 V3 V4 V5 V6 V7
# 1 13  3 20  0  0  0  0
# 2  3 10  0  0  0  6  0
# 3 20  0  5  0  0  0  0
# 4  0  0  0  7 20  0  0
# 5  0  0  0 20 19  0  0
# 6  0  0  0  0  0  8  0
# 7  0  0  0  0  0  0 13
# 
# $Table2
#    V1
# 1   0
# 2   2
# 3  10
# 4  -5
# 5   3
# 6 -10
# 7  -5

The chunkId parameter can also be a regular expression, like `chunkId = "[A-Za-z]+".



来源:https://stackoverflow.com/questions/29286531/is-it-possible-to-read-two-tables-from-the-same-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!