vendredi 9 juillet 2021

How to write a for loop with if statements across multiple columns?

One column in my dataframe in R has a direction (either Left, Right, L, or R). If a row in this column is Left or L, I am trying to convert the number in the same row in a different column to a negative value. This is the code I have written so far:

for(i in 1:nrow(df)){
  if(is.na(df[i,7]==F)){
    if(df[i,7]=="Left"  | df[i,7]=="L"){
      if(is.numeric(df[i,11])==T){
        lapply(df[i,11], all.neg)
      }
    }
  }
}

I keep getting the following error message in return:

Error in if (df[i, 7] == "Left" | df[i, 7] == "L") { : 
  missing value where TRUE/FALSE needed

I have tried to do na.pass(df) to avoid stopping after a missing value, and I included the first if statement of is.na(), which seems unnecessary. I have also gone through and made sure there were not other values like "Null" that were not being properly coded as NA. I would greatly appreciate if someone knows how to fix this issue - thanks so much!

Here is a screenshot of what the data looks like. Basically, I need for all of the values to be changed to negative if the LSTOA Direction is Left or L. enter image description here

Aucun commentaire:

Enregistrer un commentaire