6

我有数百个文本文件,每个文件中包含以下信息:

*****Auto-Corelation Results******
1     .09    -.19     .18     non-Significant

*****STATISTICS FOR MANN-KENDELL TEST******
S=  609
VAR(S)=      162409.70
Z=           1.51
Random : No trend at 95%

*****SENs STATISTICS ******
SEN SLOPE =  .24

现在,我想读取所有这些文件,并从每个文件(例如)中“收集” Sen 的统计.24信息,并与相应的文件名一起编译成一个文件。我必须在 R 中做到这一点。

我使用过 CSV 文件,但不确定如何使用文本文件。

这是我现在使用的代码:

require(gtools)
GG <- grep("*.txt", list.files(), value = TRUE)
GG<-mixedsort(GG)
S <- sapply(seq(GG), function(i){
X <- readLines(GG[i])
grep("SEN SLOPE", X, value = TRUE)
})
spl <- unlist(strsplit(S, ".*[^.0-9]"))
SenStat <- as.numeric(spl[nzchar(spl)])
SenStat<-data.frame( SenStat,file = GG)
write.table(SenStat, "sen.csv",sep = ", ",row.names = FALSE)

当前代码无法正确读取所有值并给出此错误:

Warning message:
NAs introduced by coercion 

我也没有得到输出的另一列的文件名。请帮忙!


诊断 1

代码也在读取 = 符号。这是 print(spl) 的输出

 [1] ""       "5.55"   ""       "-.18"   ""       "3.08"   ""       "3.05"   ""       "1.19"   ""       "-.32"  
[13] ""       ".22"    ""       "-.22"   ""       ".65"    ""       "1.64"   ""       "2.68"   ""       ".10"   
[25] ""       ".42"    ""       "-.44"   ""       ".49"    ""       "1.44"   ""       "=-1.07" ""       ".38"   
[37] ""       ".14"    ""       "=-2.33" ""       "4.76"   ""       ".45"    ""       ".02"    ""       "-.11"  
[49] ""       "=-2.64" ""       "-.63"   ""       "=-3.44" ""       "2.77"   ""       "2.35"   ""       "6.29"  
[61] ""       "1.20"   ""       "=-1.80" ""       "-.63"   ""       "5.83"   ""       "6.33"   ""       "5.42"  
[73] ""       ".72"    ""       "-.57"   ""       "3.52"   ""       "=-2.44" ""       "3.92"   ""       "1.99"  
[85] ""       ".77"    ""       "3.01"

诊断 2

发现了我认为的问题。负号有点棘手。在某些文件中是

SEN SLOPE =-1.07
SEN SLOPE = -.11

由于 = 之后的差距,我得到了第一个的 NA,但代码正在读取第二个。如何修改正则表达式来解决这个问题?谢谢!

4

4 回答 4

10

假设"text.txt"是您的文本文件之一。用 读入 R readLines,您可以使用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" 

然后用

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
于 2014-04-13T02:19:21.677 回答
4

首先制作一个示例文本文件:

cat('*****Auto-Corelation Results******
1     .09    -.19     .18     non-Significant

*****STATISTICS FOR MANN-KENDELL TEST******
S=  609
VAR(S)=      162409.70
Z=           1.51
Random : No trend at 95%

*****SENs STATISTICS ******
SEN SLOPE =  .24',file='samp.txt')

然后读入:

tf <- readLines('samp.txt')

现在提取适当的行:

sen_text <- grep('SEN SLOPE',tf,value=T)

然后得到超过等号的值:

sen_value <- as.numeric(unlist(strsplit(sen_text,'='))[2])

然后为每个文件组合这些结果(原始问题中没有提到文件结构)

于 2014-04-13T02:22:50.727 回答
1

如果您的文本文件始终采用这种格式(例如,Sen Slope 始终位于第 11 行)并且所有文件中的文本都是相同的,那么您只需两行即可完成您需要的操作。

char_vector <- readLines("Path/To/Document/sample.txt")
statistic <- as.numeric(strsplit(char_vector[11]," ")[[1]][5])

那会给你0.24。

然后,您通过 apply 语句或 for 循环遍历所有文件。

为了清楚起见:

> char_vector[11]
[1] "SEN SLOPE =  .24"

> strsplit(char_vector[11]," ")
[[1]]
[1] "SEN"   "SLOPE" "="     ""      ".24"  

因此,您需要 strsplit 的 [[1]] [5] 结果。

于 2014-04-13T02:21:30.063 回答
1

步骤 1:将完成保存fileNames在单个变量中:

fileNames <- dir(dataDir,full.names=TRUE)

第 2 步:让我们读取并处理其中一个文件,并确保它给出正确的结果:

data.frame(
  file=basename(fileNames[1]), 
  SEN.SLOPE= as.numeric(tail(
    strsplit(grep('SEN SLOPE',readLines(fileNames[1]),value=T),"=")[[1]],1))
  )

步骤 3:在所有设备上执行此操作fileNames

do.call(
  rbind,
  lapply(fileNames, 
         function(fileName) data.frame(
           file=basename(fileName), 
           SEN.SLOPE= as.numeric(tail(
             strsplit(grep('SEN SLOPE',
                           readLines(fileName),value=T),"=")[[1]],1)
             )
           )
         )
  )

希望这可以帮助!!

于 2014-04-24T06:59:45.613 回答