mardi 17 août 2021

Issue with NA in conditionals in for-loop

I have the following dataset:

date <- as.Date(c('2010-11-1','2010-11-2','2010-11-3','2010-11-4','2010-11-5','2010-11-6','2010-11-7','2010-11-8','2010-11-9','2010-11-10'))
precipitation <- c(0, 11, NA,3,0,0,0,7,9,10)
snowheight <- c(5,7,56,32, 11, 24, NA,8, 13, 11)
temperature <- c(-5, -2, 0, 0.4, NA, 5,6,4, 9, 10)

df <- data.frame(date, precipitation, snowheight, temperature)

I am trying to create a dichotomous variable with (0 and 1) for each datasample based on the following conditions:

  • if snowheight > 10 we continue with the conditions below. Else assign NA to the dichotomous variable.
  • if precipitation =< 0 we assign 0
  • if precipitation > 0 and temperature > 0 we assign 1.
  • if precipitation > 0 and temperature < 0 we assign 0.
  • if one of the conditional variable contains NA, NA should be assigned to the dichtomous variable as well.

I have the following loop that works fine if there is no NA in the data:

for (i in seq_len(nrow(df))){
  if (df$snowheight[i] > 10){
    if (df$precipitation[i] > 0){
      if (df$temperature[i]> 0){
        df$dicht[i] <- 1
      } else {
        df$dicht[i] <- 0
      }
    } else {
      df$dicht[i] <- 0
    }
  } else {
    df$dicht[i] <- NA
  }
}

However, since my data contains NA, I get the following error:

Error in if (df$precipitation[i] > 0) { : 
  missing value where TRUE/FALSE needed

I tried this solution but I get the same error:

for(i in seq_len(nrow(df))){
  if (is.na(df$snowheight[i])){
    df$dicht[i] <- NA
  } else if (df$snowheight[i] > 10){
    if(df$precipitation[i] > 0){
      if(df$temperature[i]> 0){
        df$dicht[i] <- 1
      } else {
        df$dicht[i] <- 0
      }
    } else {
      df$dicht[i] <- 0
    }
  } else {
    df$dicht[i] <- NA
  }
  if (is.na(df$precipitation[i])){
    df$dicht[i] <- NA
  }
  if (is.na(df$temperature[i])){
    df$dicht[i] <- NA
  }
}

Hope you can help. Let me know if you need more info. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire