假设您有一个具有以下结构的.txt文件:
>>> header
>>> header
>>> header
K L M
200 0.1 1
201 0.8 1
202 0.01 3
...
800 0.4 2
>>> end of file
50 0.1 1
75 0.78 5
...我想读取除>>>表示的行和>>> end of file行下面的行之外的所有数据。到目前为止,我已经用read.table(comment.char = ">", skip = x, nrow = y)解决了这个问题(x和y目前已经修复)。这将读取header和>>> end of file之间的数据。
但是,我想让我的函数在行数方面更具可塑性。数据的值可能大于800,因此可能会有更多的行。
我可以对文件执行scan或readLines操作,查看与>>> end of file对应的行,并计算要读取的行数。你会使用什么方法?
发布于 2011-01-08 03:18:05
这里有一种方法:
Lines <- readLines("foo.txt")
markers <- grepl(">", Lines)
want <- rle(markers)$lengths[1:2]
want <- seq.int(want[1] + 1, sum(want), by = 1)
read.table(textConnection(Lines[want]), sep = " ", header = TRUE)这就给出了:
> read.table(textConnection(Lines[want]), sep = " ", header = TRUE)
K L M
1 200 0.10 1
2 201 0.80 1
3 202 0.01 3
4 800 0.40 2在您提供的数据片段上(在文件foo.txt中,并且在删除...行)。
发布于 2011-01-08 04:14:48
这里有几种方法。
1) readLine将文件的行读入到L中,并将skip设置为要在开头跳过的行数,将end.of.file设置为标记数据结束的行号。然后,read.table命令使用这两个变量重新读取数据。
File <- "foo.txt"
L <- readLines(File)
skip <- grep("^.{0,2}[^>]", L)[1] - 1
end.of.file <- grep("^>>> end of file", L)
read.table(File, header = TRUE, skip = skip, nrow = end.of.file - skip - 2)一种变体是在read.table行中使用textConnection代替File:
read.table(textConnection(L), header = TRUE,
skip = skip, nrow = end.of.file - skip - 2)2)另一种可能是使用sed或awk/gawk。考虑一下这一行gawk程序。如果程序看到标记数据结束的行,则退出;否则,如果该行以>>>开头,则跳过当前行,如果这两行都不出现,则打印该行。我们可以通过gawk程序传输foo.txt并使用read.table读取它。
cat("/^>>> end of file/ { exit }; /^>>>/ { next }; 1\n", file = "foo.awk")
read.table(pipe('gawk -f foo.awk foo.txt'), header = TRUE)它的一个变体是,我们可以省略gawk程序的/^>>>/ {next};部分,它跳过开头的>>>行,而使用comment = ">" in theread.table`调用。
https://stackoverflow.com/questions/4629115
复制相似问题