mercredi 6 mai 2020

R logical operators: && and || vs & and |

I thought i already understood how logical operators work in [R] ... turns out that was kind of an illusion.Today I tried to build an if-condition that throws an error message if the value is NULL or the value is not found in a given vector. My first approach with the normal OR (|) did not work. My second approach with the double OR (||) seems to work ... still I am not 100 % sure why it works (and if it really works). So if someone could help me to finally understand, I really would appreciate it :D

Here is an example that should illustrate the problem in more detail:

# first approach (does not work)
check_val1 <- function(x){
  vals <- c("a","b","c")
  if (is.null(x) | !x %in% vals){
    print("wrong input")
  } else {
    print("correct input")
  }
}

# second approach (works)
check_val2 <- function(x){
  vals <- c("a","b","c")
  if (is.null(x) || !x %in% vals){
    print("wrong input")
  } else {
    print("correct input")
  }
}

check_val1(NULL)
# result: error in if (is.null(x) | !x %in% vals) { : argument is of length zero
check_val1("foo")
# result: "wrong input"
check_val1("a")
# result: "correct input"

check_val2(NULL)
# result: "wrong input"
check_val2("foo")
# result: "wrong input"
check_val2("a")
# result: "correct input"

Does the second approach work because the second part (!x %in% vals) of the condition is only evaluated if the first part (is.null(x)) is not TRUE? That would make some sense, as the condition is TRUE as soon as one part of it is TRUE. So there would be no need to evaluate the second part ... still ... this explaination seems a little bit arbitrary. Is there a better one (I already checked the documentation. The explaination provided there helps a little bit, but in the end it leaves me confused somehow ^^)

Of course I could just use two separate if statements to avoid the problem, but using one condition seems more elegant to me :D

Thanks for your help :)

Aucun commentaire:

Enregistrer un commentaire