In R, vectorized if-then-else is a way
to perform conditional operations on vectors. It is similar to the ifelse()
function, but it allows for more complex conditions and multiple true / false
results.
The ifelse() function in R is a
vectorized version of the if-else statement that allows for conditional
operations on vectors. It takes a logical condition and two vectors, and
returns a vector containing the values from the second vector where the
condition is TRUE, and the values from the third vector where the condition is
FALSE.
Syntax:
ifelse(condition,
true_vals, false_vals)
Parameters:
l
condition: A logical condition to be
tested.
l true_vals:
A vector of values to return if the condition is TRUE
l false_vals:
A vector of values to return if the condition is FALSE
Example:
#
Create a vector
x
<- c(1, 2, 3, 4, 5)
#
Use ifelse() to test if x is greater than 3
y
<- ifelse(x > 3, "Greater than 3", "Less than or equal to
3")
#
Print the results
y
Output:
[1]
"Less than or equal to 3" "Less than or equal to 3"
"Less than or equal to 3"
[4]
"Greater than 3" "Greater than
3"
In this example, we create a vector x and use ifelse() function to test if each element of x is greater than 3. If the condition is TRUE, the corresponding element of y is set to the string "Greater than 3", otherwise it is set to the string "Less than or equal to 3". The resulting vector y contains the corresponding strings for each element of x.
No comments:
Post a Comment