ifelse()
get_help()
docs
The ifelse()
function comes with R
and is part of the Base R
{base}
package.
We use this function to assign a value based on whether a logical statement is TRUE
or FALSE
.
Note that there is a {dplyr}
package version of this function (dplyr::if_else()
, with an underscore) that can be used in exactly the same way, but the {dplyr}
version enforces that the resulting values must always be the same type.
ifelse(logical statement,
if statement is `TRUE`,
value to use if statement is `FALSE`) value to use
Some examples below use the carnivores
dataset. Learn more about this dataset with get_help("carnivores")
.
# Show the carnivores dataset
carnivores
## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <dbl> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Return the value 5 if it is TRUE that 10 < 4.
# Otherwise, return the value 7.
ifelse(10 < 4, 5, 7)
## [1] 7
# Return the value 5 if it is TRUE that 10 < 100.
# Otherwise, return the value 'string'.
# Note: This will *not work* with the {dplyr} version `if_else()` since 5 is a number but 'string' is character (different types!)
ifelse(10 < 100, 5, 'string')
## [1] 5
# Use ifelse to create a new column `sleeps_alot` that will contain
# "yes" if `awake` <= 10, and "no" otherwise, using dplyr::mutate()
%>%
carnivores ::mutate(sleeps_alot = ifelse(awake <= 10, "yes", "no")) dplyr
## # A tibble: 9 × 5
## name genus awake brainwt sleeps_alot
## <chr> <fct> <dbl> <dbl> <chr>
## 1 Arctic fox Vulpes 11.5 0.0445 no
## 2 Cheetah Acinonyx 11.9 NA no
## 3 Dog Canis 13.9 0.07 no
## 4 Gray seal Haliochoerus 17.8 0.325 no
## 5 Jaguar Panthera 13.6 0.157 no
## 6 Lion Panthera 10.5 NA no
## 7 Northern fur seal Callorhinus 15.3 NA no
## 8 Red fox Vulpes 14.2 0.0504 no
## 9 Tiger Panthera 8.2 NA yes