mardi 16 juin 2020

How do "If" statements evaluate input? Is it on the vector as a whole or on each part of the vector individually?

x <- c(1:10)

only_even <- function(x){
  if(x %% 2 == 0 && is.na(x) < 1){
    return(x)
  }else{
    print("Not even or real")
  }
}
only_even(x)

Returns

"Not even or real"

even though there are clearly even numbers in X (1:10).

x <- c(1:10)

only_even <- function(x){
  if(x %% 2 == 0){
    return(x)
  }else{
    print("Not even or real")
  }
}
only_even(x)

Returns

Warning message:
In if (x%%2 == 0) { :
  the condition has length > 1 and only the first element will be used

IM confused by both results. Especially the second error "the condition has length >1 and only the first element will be used". When creating if statements, does it only apply to the vector/input as a whole? Instead of individually going through each value? Is that why im getting the error about condition has length > 1?

Aucun commentaire:

Enregistrer un commentaire