Home > Software engineering >  How to change this code more simply using for loop in R?
How to change this code more simply using for loop in R?

Time:08-22

How to change this code more simply using for loop in R? Thank you!

   for (i in 1:4) {
      data[[i]]$fa1[data[[i]]$fb1==0] <- 0 
      data[[i]]$fa2[data[[i]]$fb2==0] <- 0
      data[[i]]$fa3[data[[i]]$fb3==0] <- 0
      data[[i]]$fa4[data[[i]]$fb4==0] <- 0
      data[[i]]$fa5[data[[i]]$fb5==0] <- 0
      data[[i]]$fa6[data[[i]]$fb6==0] <- 0
      data[[i]]$fa7[data[[i]]$fb7==0] <- 0
      data[[i]]$fa8[data[[i]]$fb8==0] <- 0
      data[[i]]$fa9[data[[i]]$fb9==0] <- 0
      data[[i]]$fa10[data[[i]]$fb10==0] <- 0
      data[[i]]$fa11[data[[i]]$fb11==0] <- 0
      data[[i]]$fa12[data[[i]]$fb12==0] <- 0
      data[[i]]$fa13[data[[i]]$fb13==0] <- 0 }

CodePudding user response:

Try the following. Untested, since there are no data.
Instead of the extraction operator $, the code below uses [[ and indexes the data with character vectors of names, fa_cols and fb_cols.

fa_cols <- paste0("fa", 1:13)
fb_cols <- paste0("fb", 1:13)
for(i in 1:4) {
  for(j in seq_along(fa_cols)) {
    j_fa <- fa_cols[j]
    j_fb <- fb_cols[j]
    fb_zero <- which(data[[i]][[ j_fb ]] == 0)
    data[[i]][[ j_fa ]][ fb_zero ] <- 0
  }
}
  •  Tags:  
  • r
  • Related