Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created July 7, 2017 20:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ateucher/c7359f566eded9fcd4a255f4cbd4fe67 to your computer and use it in GitHub Desktop.
Save ateucher/c7359f566eded9fcd4a255f4cbd4fe67 to your computer and use it in GitHub Desktop.
R: if vs ifelse

R: if vs ifelse

Inspired by a question about when to use if vs ifelse

First we'll make a simple function that determines whether or not someone is awesome:

is_awesome <- function(name) {
  name %in% c("Heather", "Andy", "Steph", "Jon")
}

Test the function:

is_awesome("Jon")
## [1] TRUE
is_awesome("Heathcliff")
## [1] FALSE
is_awesome(c("Steph", "Heather", "Cuthbert"))
## [1]  TRUE  TRUE FALSE

The if function is designed to work with things that are length 1, like a single name:

if (is_awesome("Heather")) {
  print("Yay")
} else {
  print("Boo")
}
## [1] "Yay"

If we try to use if and else with things that are longer than one, we get a warning, and an unexpected answer:

if (is_awesome(c("Andy", "Heather", "Steph", "Jon", "Bill"))) {
  print("Yay")
} else {
  print("Boo")
}
## Warning in if (is_awesome(c("Andy", "Heather", "Steph", "Jon", "Bill"))) {:
## the condition has length > 1 and only the first element will be used

## [1] "Yay"

If we want to work with vectors that are length > 1, use ifelse

ifelse(is_awesome(c("Andy", "Heather", "Steph", "Jon", "Bill")), "Yay", "Boo")
## [1] "Yay" "Yay" "Yay" "Yay" "Boo"
@khanhung2104
Copy link

Sincerely thank you for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment