samedi 30 mars 2019

How to fix 'Error in if (p_change[j] == dat[i, 1]) { : missing value where TRUE/FALSE needed' in a loop?

I am new to R. I am running a loop which basically compares the values contained in a vector (p_change) with the values in a column of a data frame (dat). In case the number coincides, I want a value of the same row but a different column to be subtracted by one. This is a sample of the vector (p_change):

p_change <- c(30101,92901,92031,90630,90282,10401)

The data frame (dat) to which it is compared is as follows: enter image description here

The for loop that I am running is this one:

for (i in 1:nrow(dat)) {
  for (j in 1:length(p_change)) {
    if (p_change[j]==dat[i,1]) {
      dat[i,4] <- 1-dat[i,4] # Subtraction of a unit (polarity change)
    } else {
      i = i+1
    }
  }
}

However, after running it, it throws me the following error 'Error in if (p_change[j] == dat[i, 1]) { : missing value where TRUE/FALSE needed'. I was wondering if you spot the glitch that causes the error. Thanks!

Aucun commentaire:

Enregistrer un commentaire