mardi 1 décembre 2020

Incorrect function output when passing NA as arguments in R

I am trying to set a range based on numerical arguments, The function is working fine for every case except when the two arguments are NA;

I would like the function to return NA when x and y are NA's, however it keeps me returning a different output..

Here's my code:


set_range_function <- function(x, y){
   if(x == 0 && y %in% c(0,1,2)){
                                  return("Menos de 3 meses")
   } else if(x == 0 && y %in% c(3,4,5)){
                                  return("Entre 3 e 6 meses")
   } else if(x == 0 && y %in% c(6,7,8,9,10,11)){
                                  return("Entre 6 e 12 meses")
   } else if(x == 1 && !is.null(y)){
                                  return("Entre 1 a 2 anos") 
   } else if(x == 2 && !is.null(y)){
                                  return("Entre 2 a 3 anos")
   } else if(x %in% c(3,4) && !is.null(y)){
                                  return("Entre 3 e 5 anos")
   } else if(x %in% c(5,6,7,8,9) && !is.null(y)){
                                  return("Entre 5 e 10 anos")
   } else if(x >= 10 && !is.null(y)){
                                  return("Mais de 10 anos")
   } else if(is.na(x) && is.na(y)){
                                  return(NA)
   }  else {
              return(NA)
   }
}


set_range_function(NA, NA)


Console output:

Error in if (x == 1 && !is.null(y)) { : 
  missing value where TRUE/FALSE is required

Expected output:

set_range_function(NA, NA)

[1] NA

Aucun commentaire:

Enregistrer un commentaire