vendredi 30 mars 2018

A loop to iterate over different data.frames

This is a little tough to explain but I will do my best. I get several datasets with different tests in different terms (Fall, Winter, Spring, Summer). The terms are loaded into the variable "term". The tests are labeled Test1, Test2, Test3, Test4, Test5. I was able to make an IF statement that takes into account these different Terms, and does some other functions I need completed. Everything works great but I need to write a looping function to iterate over the 5 different tests. I have been trying to find out how to do this but have not been able to. You do not need to pay much attention to what is in the function I am just wondering is I can iterate that function over Test1,Test2,Test3,Test4,and Test5. The current if statment is:

if(is.data.frame(Test1)){
  if(term== "Fall"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Fall", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Winter"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Winter", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Spring"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Spring", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Summer"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Summer", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }
}

I tried

L <- list(Test1,Test2,Test3,Test4,Test5)

for(i in L)
{if(is.data.frame(Test1)){
  if(term== "Fall"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Fall", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Winter"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Winter", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Spring"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Spring", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }else if(term== "Summer"){
    Subject1<-gsub("IQ", "", variable.names(Test1[9]))
    Subject1<-gsub("Summer", "", Subject1)
    n1 <- nrow(Test1)
    Test1$Subject <- rep(Subject1, length.out = n1)
  }
}

This did not work but I think it is close to working. Any guidance would be greatly appreciated. Again the function does not need to be paid much attention to just the ability to iterate over the 5 tests.

Thank you

Aucun commentaire:

Enregistrer un commentaire