MlolM
MlolM

Reputation: 247

Read files through loops and grep result

I write up a loop to grep my working result from files.

Below is something I've done.

At the end, I only can get result from the final item of j loop.

How can I revise my script?

Get_all <- as.data.frame(NULL)

  for (j in c("AreaA")){
    for (k in c("CaseA","CaseB")){  # for caseA and caseB.
          result_file <- paste0(link,j,"/",k)

          if (S=="target"){
            A <- subset(Estimation, V2==1 )[,c(1,4)]    
            name_1 <- (read.table(file,skip= (grep('Add', readLines(file))),nrows=1))
            v1 <- cbind(name_1$V4,A$V4[[1]])

          }

          if (KQ=="target"){  
            B <- subset(Estimation, V2==3)[,c(1,4)]     
            name_2 <- (read.table(file,skip= (grep('Loat', readLines(file))),nrows=1))
            v2 <- cbind(name_2$V4,B$V4[[1]])
          }     
        }
        ifelse(k=="CaseA", re<-rbind(v1, v2), var<-rbind(v)) 
      }    

Upvotes: 0

Views: 86

Answers (1)

MPhD
MPhD

Reputation: 456

You have a loop within a loop here, and you are only rbinding results of the 2nd loop, so the inner loop (which does case a vs b) is only producing the second result (case b). Try adjusting the middle loop as follows:

for (k in c("CaseA","CaseB")){  # for caseA and caseB.
          result_file <- paste0("xxxx/",j,"/",k)
          Estimation_parament = read.table(result_file)

          if (N_row==30){
            file = "M3.Rout"

            trait1 <- subset(Estimation_parament, V2==1 & V3==1)[,c(1,4)]   
            name_1 <- (read.table(file,skip= (grep('#grepMe1#', readLines(file))+0),nrows=1)[4])
            variance1 <- cbind(name_1$V4,trait1$V4[[1]])
          }
          if (N_row==50){  
            file = "M5.Rout"

            trait2 <- subset(Estimation_parament, V2==3 & V3==3)[,c(1,4)]     
            name_2 <- (read.table(file,skip= (grep('#grepMe1#', readLines(file))+2),nrows=1)[4])
            variance2 <- cbind(name_2$V4,trait2$V4[[1]])
          }    
          ifelse(k=="CaseA", variance<-rbind(variance1, variance2), variance<-rbind(variance,variance1,variance)) 
          #this will keep Case A and add on to it once you're in CaseB
        }

You need to similarly adjust the second loop, as (at the moment) you are presumably only getting output from 5traits...(overwriting the 3traits files when you redefine Get_all.

Upvotes: 1

Related Questions