vendredi 24 janvier 2020

I cant get rid of the NA no matter what i try - missing Value where TRUE/FALSE needed

I was trying to optimize my loop but I came across an issue and I havent found any direct solution here. I already checked out other threads like Error in if/while (condition) {: missing Value where TRUE/FALSE needed but it doesnt help me solving my problem I still have the same issue.

This is my code:

output <- character (nrow(df)) # predefine the length and type of the vector
condition <- (df$price < df$high & df$price > df$low)   # condition check outside the loop

system.time({
    for (i in 1:nrow(df)) {
        if (condition[i]) {
            output[i] <- "1"
         }else if (!condition[i]){
           output[i] <- "0"
        }else  {
            output[i] <- NA
        }
    }
    df$output <- output
})


I am basically checking if my price is in a certain range. If its inside the range i assign it a 1 and if its outside the range I assign it a 0. However, I have couple NA values and then my loop stops the moment i reach an NA.

Below you can see the working code if I filter out the NAs. But I would like to have a way which would handle the NAs as well.

df<- df%>% filter(!is.na(price))
output <- character (nrow(df)) # predefine the length and type of the vector
condition <- (df$price < df$high & df$price > df$low)   # condition check outside the loop


system.time({
  for (i in 1:nrow(df)) {
    if (condition[i]) {
      output[i] <- "1"
    }else  {
      output[i] <- "0"
    }
  }
  df$output <- output
})

Any idea how I could handle the NAs?

Aucun commentaire:

Enregistrer un commentaire