簡體   English   中英

在 R 的循環中使用 grep、grepl 和 regexpr

[英]Using grep, grepl and regexpr within loops in R

我想使用 grep、grepl 和 regexpr 從文本文件中自動提取某些信息。 我有一個代碼,當我為每個單獨的文件執行此操作時,它可以工作,但是我無法使循環正常工作,無法為我的工作目錄中的所有文件自動執行此過程。

由於數據的結構,我將 txt 文件作為字符串讀取。 循環似乎根據目錄中的文件數多次迭代第一個文件,顯然是因為for語句中的length(txtfiles)命令。

txtfiles = list.files(pattern="*.txt")

for (i in 1:length(txtfiles)){
all_data <- readLines(txtfiles[i])

#select hours of operation 
hours_op[i] <- all_data[hours_of_operation <- grep("Annual Hours of Operation:",all_data)]
hours_op[i] <-regmatches(hours_op, regexpr("[0-9]{1,9}.[0-9]{1,9}",hours_op))

}

如果有人能指出我正確的方向來為每個文件重復這個例程,而不是多次重復同一個文件,我將不勝感激。 我想得到一個文件名列表和相應的hours_op

您需要為每個對hours_op[i]引用添加一個索引 ( [i] ),如下所示:

for (i in 1:length(txtfiles)){
    all_data <- readLines(txtfiles[i])
    hours_op[i] <- all_data[hours_of_operation <- grep("Annual Hours of Operation:",all_data)]
    hours_op[i] <-regmatches(hours_op[i], regexpr("[0-9]{1,9}.[0-9]{1,9}",hours_op[i]))
}

或者更好的是,使用臨時變量:

for (i in 1:length(txtfiles)){
    all_data <- readLines(txtfiles[i])
    temp <- all_data[hours_of_operation <- grep("Annual Hours of Operation:",all_data)]
    hours_op[i] <-regmatches(temp, regexpr("[0-9]{1,9}.[0-9]{1,9}",temp))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM