ifelse() Function in R

ifelse() function in R

The built-in ifelse() function in R allows you to conduct a logical test and return values based on the result of the test.

The basic syntax for the ifelse() function is as follows:

ifelse(test_expression, value if TRUE, value if FALSE)

The following code illustrates a few examples of the ifelse() function in action:

#ifelse() example with a vector
x <- c(1, 3, 6)
ifelse(x > 5, "greater_than_5", "not_greater_than_5")

#[1] "not_greater_than_5" "not_greater_than_5" "greater_than_5" 

#ifelse() example with a data frame
data <- data.frame(team_abb = c("A", "B", "B", "B", "A"),
                   score = c(12, 15, 17, 24, 30))
data$team_name <- ifelse(data$team_abb == "A", "Angels", "Bruins")

#  team_abb score team_name
#1        A    12    Angels
#2        B    15    Bruins
#3        B    17    Bruins

Leave a Reply

Your email address will not be published. Required fields are marked *