我有一个这样的 file.txt,我想在 R 中读取它直到找到匹配项:
header1
header2
more descriptions
again
stop here
dataline1
dataline2
dataline3
在这种情况下,匹配将是“停在这里”。
我想通过以下方式做到这一点:
x<-file("file.txt","r")
match<-paste("stop","here")
line<-readLines(x,1)
while(line!=match){
line<-readLines(x,1)
}
line
[1] "stop here"
问题是停止行可以有更多的字符串,也就是说,除了“在这里停止”之外,还可以像“在这里停止某物”,其中某些东西可以从一个文件到另一个文件发生变化。 当尝试使用上面的代码读取这个新文件时,它会抛出一个错误:
Error in while (line != match) { : argument is of length zero
并且行是空的。
line
character(0)
我试过使用 collapse 和 grep,但出现了同样的错误。
match<-paste("stop","here", collapse = "|")
while(line!=grep(match, line)){
有什么办法可以解决这个问题吗? 谢谢
最佳答案
您可以使用 grepl
而不是 grep
因为它直接返回一个 logical
x <- file("file.txt", "r")
line <- readLines(x, 1)
while(!grepl("^stop here.+", line)) {
line <- readLines(x, 1)
}
https://stackoverflow.com/questions/29258080/