Assume "text.txt"
是您的文本文件之一。读入 RreadLines
, 您可以使用grep
找到包含的行SEN SLOPE
。没有进一步的争论,grep
返回找到正则表达式的元素的索引号。这里我们发现是第11行。添加value = TRUE
参数来获取该行所读取的内容。
x <- readLines("text.txt")
grep("SEN SLOPE", x)
## [1] 11
( gg <- grep("SEN SLOPE", x, value = TRUE) )
## [1] "SEN SLOPE = .24"
为了找到所有的.txt
我们可以使用工作目录中的文件list.files
用正则表达式。
list.files(pattern = "*.txt")
## [1] "text.txt"
循环多个文件
我创建了第二个文本文件,text2.txt
与不同的SEN SLOPE
值来说明我如何在多个文件上应用此方法。我们可以用sapply
, 其次是strsplit
,得到spl
所需的值。
GG <- list.files(pattern = "*.txt")
S <- sapply(seq_along(GG), function(i){
X <- readLines(GG[i])
ifelse(length(X) > 0, grep("SEN SLOPE", X, value = TRUE), NA)
## added 04/23/14 to account for empty files (as per comment)
})
spl <- unlist(strsplit(S, split = ".*((=|(\\s=))|(=\\s|\\s=\\s))"))
## above regex changed to capture up to and including "=" and
## surrounding space, if any - 04/23/14 (as per comment)
SenStat <- as.numeric(spl[nzchar(spl)])
然后我们可以将结果放入数据帧并将其发送到文件write.table
( SenStatDf <- data.frame(SenStat, file = GG) )
## SenStat file
## 1 0.46 text2.txt
## 2 0.24 text.txt
我们可以将其写入文件
write.table(SenStatDf, "myFile.csv", sep = ", ", row.names = FALSE)
2014 年 7 月 21 日更新:
由于结果被写入文件,因此可以使这变得更加简单(并且更快)
( SenStatDf <- cbind(
SenSlope = c(lapply(GG, function(x){
y <- readLines(x)
z <- y[grepl("SEN SLOPE", y)]
unlist(strsplit(z, split = ".*=\\s+"))[-1]
}), recursive = TRUE),
file = GG
) )
# SenSlope file
# [1,] ".46" "test2.txt"
# [2,] ".24" "test.txt"
然后写入并读入 R
write.table(SenStatDf, "myFile.txt", row.names = FALSE)
read.table("myFile.txt", header = TRUE)
# SenSlope file
# 1 1.24 test2.txt
# 2 0.24 test.txt