R Programming language - R ifelse() Function
In R programming language, the ifelse()
function is a vectorized version of the if...else
statement, which allows you to apply the if...else
logic to each element of a vector or array.
The general syntax of the ifelse()
function is as follows:
ifelse(condition, true_value, false_value)
The condition
is a Boolean expression that evaluates to either TRUE or FALSE. If the condition is TRUE, the true_value
is returned; otherwise, the false_value
is returned.
Here is an example of using the ifelse()
function in R:
x <- c(1, 2, 3, 4, 5) ifelse(x > 3, "high", "low")
In this example, the condition
is x > 3
. Since the first three elements of x
are less than or equal to 3, and the last two elements are greater than 3, the output will be a character vector of length 5, with the first three elements set to "low" and the last two elements set to "high".
You can also use nested ifelse()
functions to test multiple conditions. The general syntax for nested ifelse()
functions is as follows:
ifelse(condition1, true_value1, ifelse(condition2, true_value2, ifelse(condition3, true_value3, false_value)))
Here is an example of a nested ifelse()
function in R:
x <- c(1, 2, 3, 4, 5) ifelse(x > 3, "high", ifelse(x == 3, "medium", "low"))
In this example, the first condition
is x > 3
, the second condition
is x == 3
, and the false_value
is "low". Since the first three elements of x
are less than or equal to 3, the output will be a character vector of length 5, with the first three elements set to "low", the fourth element set to "high", and the fifth element set to "high".