vendredi 22 novembre 2019

Struggling to get while statement to continue iterating over each row in R

I am attempting to use a loop to balance out rows of data, based on the value in the first column of each. The below is just an example, ultimately I want to run something similar to this based on max and min values across columns in a larger dataset.

If the first column is a number below 11, I want to increase it slightly and reduce the second and third columns by a corresponding value. I also want to state if any of the V1 values are above a certain level.

I've tried various code and either receive a warning message regarding the condition having length > 1, or the break clause is immediately achieved. See code below.

mat <- matrix(data = seq(10, 21, by=1), nrow = 6, ncol =3 )
mat <- as.data.frame(mat)
continue <- TRUE
while(continue) {
  for(i in 1:nrow(mat)) {
    if(mat[i,1] > 12) {
      mat[i, "V1"] <- "high"
    } else if (mat[i,1] < 11) {
      mat[i, "V1"] <- mat$V1[i] + 0.1;
      mat[i, "V2"] <- mat$V2[i] - 0.03;
      mat[i, "V3"] <- mat$V3[i] - 0.07
      print(paste("V1", mat$V1))
    } else if (mat[i,1] > 11) {
      continue <- FALSE
    }
  }
}

I am assuming that the final else if statement is checking all of the values in the first column, and is therefore seeing that the condition has been met. However I want the code to carry on iterating until every row meets the condition.

Aucun commentaire:

Enregistrer un commentaire