The “if_else” Function in R
Package: dplyr
Purpose: To perform element-wise conditional operations on vectors or data frames.
General Class: Data Manipulation
Required Argument(s):
condition: A logical vector indicating which elements should be updated.
true: The value to assign to elements where condition is TRUE.
false: The value to assign to elements where condition is FALSE.
Notable Optional Arguments:
None.
Example (with Explanation):
# Load necessary packages
library(dplyr)
# Create a sample data frame
data <- data.frame(
ID = c(1, 2, 3, 4, 5),
value = c(10, 15, 20, 25, 30)
)
# Create a new column 'category' based on a condition
result <- data %>%
mutate(category = if_else(value > 20, "High", "Low"))
# Display the result
print(result)In this example, the if_else function from the dplyr package is used to create a new column ‘category’ in the sample data frame data. The ‘category’ column is assigned the value “High” if the corresponding value in the ‘value’ column is greater than 20, otherwise it is assigned the value “Low”. The result is a new data frame result containing the original data along with the newly created ‘category’ column.