gpt4 book ai didi

r - 一种过滤文本文件的算法

转载 作者:行者123 更新时间:2023-12-04 01:40:32 24 4
gpt4 key购买 nike

假设你有一个 .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) 解决了这个问题( xy 当前已修复)。这将读取标题和 >>> end of file 之间的数据。 .

但是,我想让我的函数在行数方面更具可塑性。数据的值可能大于 800,因此行数可能会更多。

我可以 scanreadLines文件并查看哪一行对应于 >>> end of file并计算要读取的行数。你会使用什么方法?

最佳答案

这是一种方法:

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 中,并在删除 ... 行之后)。

关于r - 一种过滤文本文件的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4629115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com