The “ifelse” Function in R
Package: Base R (no specific package required)
Purpose: Provides a vectorized way to perform conditional (if-else) operations on elements of a vector.
General Class: Data Transformation
Required Argument(s):
test: A logical vector indicating which elements should be selected.
yes: Values to be assigned to elements where test is TRUE.
no: Values to be assigned to elements where test is FALSE.
Notable Optional Arguments:
None
Example:
# Example data for using the ifelse function
ages <- c(25, 30, 22, 28, 35)
# Create a new vector based on a condition using ifelse
age_category <- ifelse(ages > 30, "Old", "Young")
# Display the result
print(age_category)In this example, the ifelse function is used to create a new vector (age_category) based on a condition (whether ages are greater than 30). If the condition is TRUE, the corresponding element in age_category is assigned the value “Old”; otherwise, it is assigned the value “Young”. The ifelse function allows for vectorized conditional operations on entire vectors.