0
0
R Programmingprogramming~5 mins

Ifelse vectorized function in R Programming

Choose your learning style9 modes available
Introduction
The ifelse function helps you quickly choose values from two options based on a condition for many items at once.
You want to label numbers as 'big' or 'small' depending on their size.
You need to replace missing values in a list with a default value.
You want to create a new list showing 'pass' or 'fail' based on scores.
You want to change colors in a list based on a condition.
Syntax
R Programming
ifelse(test_expression, yes, no)
test_expression is a condition checked for each item in a vector.
yes is the value chosen if the condition is TRUE; no is chosen if FALSE.
Examples
Checks each number in x; if greater than 10, returns 'big', else 'small'.
R Programming
x <- c(5, 10, 15)
ifelse(x > 10, "big", "small")
Labels scores 60 or above as 'pass', others as 'fail'.
R Programming
scores <- c(80, 55, 90)
ifelse(scores >= 60, "pass", "fail")
Replaces missing values (NA) with 0, keeps others unchanged.
R Programming
values <- c(NA, 2, NA, 4)
ifelse(is.na(values), 0, values)
Sample Program
This program labels each age as 'adult' if 18 or older, otherwise 'child'.
R Programming
ages <- c(12, 25, 17, 30)
labels <- ifelse(ages >= 18, "adult", "child")
print(labels)
OutputSuccess
Important Notes
ifelse works on whole vectors at once, so it is faster and simpler than writing loops.
The output vector has the same length as the input test_expression vector.
You can use ifelse inside other functions to quickly create new data.
Summary
ifelse lets you pick values based on a condition for many items at once.
It returns a new vector with values chosen from 'yes' or 'no' options.
Use it to quickly label, replace, or change values without loops.