是否可以从同一个文本文件中读取两个表? [英] Is it possible to read two tables from the same text file?

查看:47
本文介绍了是否可以从同一个文本文件中读取两个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个包含以下文本的文本文件 (mytext.txt):

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?

这样,如果我打印我的数据表 1,我将得到第一个表,如果我打印我的数据表 2,我将得到第二个表.

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.

我知道如果 mytext.txt 只有一张表,我可以执行以下操作:

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

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

推荐答案

1) 假设输入文件是tables.txt,将行读入Lines 并让 names.ix 成为包含表名的行的索引——这些行被标识为以不是减号或数字的字符开头.然后创建一个分组变量 grp 来标识每行属于哪个表,将这些行分成这些组并读取每组行.这不使用包,可以处理文件中任意数量的表.

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)

给予:

> 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) 顺便说一句,如果您只需要第一个表,那么这样做:

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

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

这篇关于是否可以从同一个文本文件中读取两个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆