0
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?

Kevin Lee
  • 321
  • 2
  • 8
  • 2
    the vectorised form of `if` is `ifelse`. See for example https://stackoverflow.com/questions/4042413/vectorized-if-statement-in-r and https://stackoverflow.com/questions/43877429/r-vectorized-if-for-multiple-conditions – efz Jun 16 '20 at 14:45
  • Not sure this really answer's your question. But the `ifelse( )` function IS vectorized. Try `ifelse(x %% 2 == 0,x,"Not even or real")` – Daniel O Jun 16 '20 at 14:45
  • Try that condition: `if(any(x %% 2 == 0) & sum(is.na(x)) < 1){ ...` – markus Jun 16 '20 at 14:49
  • I see. so, "if" is really for evaluating a single condition. for "vectorized" if forms, i.e. if statements that evaluate each number or part of a vector individually i should use ifelse or use another function like any – Kevin Lee Jun 16 '20 at 14:54

1 Answers1

0

As was mentioned in the comments, ifelse() is the vectorized version of if(). You're right that if() is for evaluating a single condition -- specifically, it's for evaluating the first condition if it is supplied with a boolean vector input.

x <- 1:5
y <- rep(3, 5)

ifelse(x > y, "yes", "no")
## [1] "no"  "no"  "no"  "yes" "yes"

if(x > y) "yes" else "no"
## [1] "no"
## Warning message:
## In if (x > y) "yes" else "no" :
##  the condition has length > 1 and only the first element will be used

Of course, things like any(), all(), etc. can be used to collapse a boolean vector into a single boolean element for use with vanilla if().

Aaron Montgomery
  • 1,387
  • 8
  • 11