是否可以从同一个文本文件中读取两个表?
Is it possible to read two tables from the same text file?
例如,如果我有一个包含以下文本的文本文件 (mytext.txt):
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
我可以同时检索它们并获得两个 table 吗?
所以如果我打印我的数据 table1 我会得到第一个 table 如果我打印我的数据 table 2 我会得到第二个 table .
我知道如果 mytext.txt 只有一个 table 我可以做类似的事情:
table1 <- read.table("mytext.txt")
1) 假设输入文件是 tables.txt
,将行读入 Lines
并让 names.ix
成为行的索引包含 table 个名称——这些行被标识为以不是减号或数字的字符开头。然后创建一个分组变量 grp
来标识每行属于哪个 table ,将这些行分成这些组并读取每组行。这不使用包,可以处理文件中任意数量的 table。
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) 顺便说一下,如果你只需要第一个 table 那么这样做:
library(data.table)
fread("tables.txt")
不是直接的,但你可以从我的 "SOfun" 包中尝试 read.mtable
,available only on GitHub。
该方法类似于@G.Grothendieck的方法,但是封装成一个函数,所以你可以简单地做:
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
chunkId
参数也可以是正则表达式,如`chunkId = "[A-Za-z]+".
例如,如果我有一个包含以下文本的文本文件 (mytext.txt):
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
我可以同时检索它们并获得两个 table 吗?
所以如果我打印我的数据 table1 我会得到第一个 table 如果我打印我的数据 table 2 我会得到第二个 table .
我知道如果 mytext.txt 只有一个 table 我可以做类似的事情:
table1 <- read.table("mytext.txt")
1) 假设输入文件是 tables.txt
,将行读入 Lines
并让 names.ix
成为行的索引包含 table 个名称——这些行被标识为以不是减号或数字的字符开头。然后创建一个分组变量 grp
来标识每行属于哪个 table ,将这些行分成这些组并读取每组行。这不使用包,可以处理文件中任意数量的 table。
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) 顺便说一下,如果你只需要第一个 table 那么这样做:
library(data.table)
fread("tables.txt")
不是直接的,但你可以从我的 "SOfun" 包中尝试 read.mtable
,available only on GitHub。
该方法类似于@G.Grothendieck的方法,但是封装成一个函数,所以你可以简单地做:
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
chunkId
参数也可以是正则表达式,如`chunkId = "[A-Za-z]+".