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"
Sincerely thank you for this!