Thursday 28 September 2017

R If Eles Vectorized vs Non-Vectorized

Cited from the Book "Beginning Data Sciences in R"

You cannot use "if else" for vectorized expressions, and if you give the Boolean expression a vector, R program will evaluate the first element in the vector.

x <- 1:5
if (x > 3) "bar" else "baz"
## Warning in if (x > 3) "bar" else "baz": the
## condition has length > 1 and only the first
## element will be used
## [1] "baz


If you want a vectorized version of if statements, you can instead use the ifelse function:

x <- 1:5ifelse(x > 3, "bar", "baz")
## [1] "baz" "baz" "baz" "bar" "bar


maybe_square <- function(x) {
  if (x %% 2 == 0) {
    x ** 2

  } else {
    x
  }
}
maybe_square(1:5)
## Warning in if (x%%2 == 0) {: the condition has
## length > 1 and only the first element will be used
## [1] 1 2 3 4 5


maybe_square <- Vectorize(maybe_square)maybe_square(1:5)
 

 




No comments:

Post a Comment