jeudi 16 juin 2016

Automation with if statement [R]

i have a code with the following structure:

  data input for file1
  data input for file2
  merge of file1 and file2
    first <- T
    v <- colnames(file2)
    v <- v[,-1] #first col is always ID number with i do not need in v
    for (r in v) {

    loop makes calculations

    if (first){
    results <- qa1
    first <- F
    } else {
    results <- rbind(results, qa1)
  }
}
write.table to output all the calculations from the loop

So in this loop (r in v) i receive an output of calculations based on things in the input files. I have n-number of files and i am trying to automate the process which is: you make calculations based on the file, then you take the second file you need and make calculations on it as well, then you combine the results of the calculations for the two files via rbind statement. I tried putting another loop around the one above. Then i tell it to take a file name from a "list" and put that name into the "data input for file2" for example so the two merge with the next row and all calculations go for the file specified. Example:

   data input for file1
    k <- list.files()
    for (i in k){
    data input for file2 <- read.table/read.csv(i)
    merge of file1 and file2
    first <- T
    v <- colnames(file2)
    for (r in v) { calculations based on file2 colnames}         
    }
    }

I tried using the same if statement in the for (i in k) loop but for some reason the code breaks and it does not output anything other then the first file computations. Would you please suggest a way i can do this? Thank you!

Aucun commentaire:

Enregistrer un commentaire