Home > Back-end >  How to fetch the values of dynamically generated variables by for loop in R
How to fetch the values of dynamically generated variables by for loop in R

Time:09-22

mydata2 <- maydata1
# x == 10
alpha <- 0.63
beta <- 0.2

for (i in 1:x) {
j <- i  1
  for(i in 1:j){
    CurColumn  <- mydata2[row,paste0("Columns",i)]
    NextColumn <- mydata2[row,paste0("Columns",j)] 
    DiffColumn <- NextColumn - CurColumn
    if ( (CurColumn <= alpha & alpha <= NextColumn) | ( DiffColumn < beta)) {
      mydata2$T1 <- CurColumn
      mydata2$T2 <- NextColumn
      CurActParams  <- mydata2[row,paste0("AP",i)]
      NextActParams <- mydata2[row,paste0("AP",j)] 
      break
    }
  }
} 

Attached the data frame for reference, i need help in calculating T1 and T2, based on conditions of code.

While executing code i'm not able to exact the column name using paste function, it is returning as a String.

For instance: "Columns0" is returned, mydata$"Columns0" and what i'm expecting is the column should be like mydata$Columns0, so that value can be assigned to new variable.

enter image description here

CodePudding user response:

This worked for me, hoping it'll be helpful to someone.

#x == 10
alpha <- 0.63
beta <- 0.2

for (row in 1:nrow(mydata)) {
        for (i in 0:22) {
          j <- i   1
          CurColumn  <-
            mydata[row, paste0("Column", i)]
          NextColumn <-
            mydata[row, paste0("Column", j)]
          CurAP  <-
            mydata[row, paste0("AP", i)]
          NextAP <-
            mydata[row, paste0("AP", j)]
          
          Diff <- NextColumn - CurColumn
          
          if (((CurColumn <= myda$alpha) |
               (is.na(CurColumn)))
              &
              ((myda$alpha <= NextColumn) |
               (is.na(NextColumn)))
              |
              (DiffColumn < beta)) {
            mydata$T1 <- CurColumn
            mydata$T2 <- NextColumn
            mydata$V1 <- CurAP
            mydata$V2 <- NextAP
            break
            }
        }
    } 

  • Related