在 RStudio 中遍历文本时,我可以跳过直到到达某一行吗?

Can I skip until I reach a certain line when iterating through text in RStudio?

我正在使用 read.delim() -&- read.delim2() 方法读取文本数据。他们接受一个跳过参数,但它适用于行数,(即它跳过你传递给它的行 2,3,4,100)。

我正在使用这些方法...

read.delim()

read.delim2()

...读取文本数据。因此,上述方法能够 跳过 行;这些方法有一个 skip 参数 ,并且该参数接受一个行号数组作为参数。 行号传递给skip参数的所有行号都会被reader方法跳过(即,reader 方法 不读取这些行)。

我想遍历一段文本,跳过每一行,直到到达特定行。有谁知道如何做到这一点?

你不能在基本 R 函数中这样做,而且我不知道 直接 提供的包。不过,这里有两种方法可以达到效果。

首先,一个名为file.txt的文件:

I want to skip this
and this too
Absolute Irradiance
I need this line
txt <- readLines("file.txt")
txt[cumany(grepl("Absolute Irradiance", txt))]
# [1] "Absolute Irradiance" "I need this line"   

如果您不想要“辐照度”行但想要它后面的所有内容,请添加 [-1] 以删除返回的第一行:

txt[cumany(grepl("Absolute Irradiance", txt))][-1]
# [1] "I need this line"

如果文件比较大,不想全部读入R,那么

system2("sed", c("-ne", "'/Absolute Irradiance/,$p'", "file.txt"), stdout = TRUE)
# [1] "Absolute Irradiance" "I need this line"   

这第二种技术真的不是那么好...从 file.txt 到第二个(临时)文件,然后 readLines("tempfile.txt") 直接 运行 可能更好。