mercredi 18 mars 2015

Indexing within loops

I would like to change the indexing within a loop based on criteria (the presence or absence of data within each file) when I read in data from a working directory. The data is a string, hence I'm using grep, grepl, regexpr and regmatches. Here is an example:



setwd(example)
txtfiles = list.files(pattern="^[^.].*\\.txt$")
for (i in 1:length(txtfiles)){
all_data <- readLines(txtfiles[i])
temp <- any(grepl(" CONTROLLED REGENERATOR EMISSIONS", all_data))
cre[i] = ifelse(temp, '6', '5')
temp <- all_data[wetgas_ch4 <- grep("Methane",all_data)] [cre[i]]
wg_ch4[i] <-regmatches(temp, regexpr("[0-9]{1,9}.[e-e0-9]{1,9}[+-][0-9]{1,9}",temp))

}


The first part of this code:



temp <- any(grepl(" CONTROLLED REGENERATOR EMISSIONS", all_data)) cre[i] = ifelse(temp, '6', '5')


Gets me what I want which is:



[1] "5" "5" "5" "5" "5" "6" "6" "6" "6" "5" "6" "6" "6" "6" "6" "6" "5" "6" "6"
[20] "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6"
[39] "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "5" "6"
[58] "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6" "6"
[77] "6" "6" "6" "6" "6" "6" "6" "6" "6" "5" "6" "6"


I would like to use these numbers to change the indexing in the second half. So that it would either be:



temp <- all_data[wetgas_ch4 <- grep("Methane",all_data)] [5]


Or:



temp <- all_data[wetgas_ch4 <- grep("Methane",all_data)] [6]


However, I cannot seem to get it to do this when running it in a loop. I've tried leaving it as [cre], [cre][i] and [cre[i]]. Any hints would be welcome!


Aucun commentaire:

Enregistrer un commentaire