R Func Ifelse
# R ifelse() Function - Vectorized Conditional Judgment
[ R Language Examples](https://example.com/r/r-examples.html)
The R ifelse() function is used for element-wise conditional judgment and assignment on vectors.
ifelse() is the vectorized version of if...else, which can process the entire vector at once and is more efficient than loops.
The syntax of the ifelse() function is as follows:
ifelse(test, yes, no)
**Parameter Description:**
* **test**: Logical condition expression.
* **yes**: Value returned when condition is TRUE.
* **no**: Value returned when condition is FALSE.
## Example
scores <-c(85, 92, 78, 95, 88, 72, 90, 68, 82, 89)
# Use ifelse to determine pass/fail
result <-ifelse(scores >=60, "Pass", "Fail")
print("Pass Judgment:")
print(result)
# Multi-level judgment (nested ifelse)
grade <-ifelse(scores >=90, "Excellent",
ifelse(scores >=80, "Good",
ifelse(scores >=70, "Average",
ifelse(scores >=60, "Pass", "Fail"))))
print("Grade Judgment:")
print(grade)
Executing the above code produces the following output:
"Pass Judgment:" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass" "Grade Judgment:" "Good" "Excellent" "Average" "Excellent" "Good" "Average" "Excellent" "Pass" "Good" "Good"
ifelse() can also be used for data cleaning and value replacement:
## Example
# Data cleaning: Replace negative values with 0
values <-c(10, -5, 20, -3, 15, -8, 25)
cleaned <-ifelse(values <0, 0, values)
print("Replace negative values with 0:")
print(cleaned)
# Missing value replacement
data_with_na <-c(10, NA, 20, NA, 30)
replaced <-ifelse(is.na(data_with_na), 0, data_with_na)
print("Replace NA with 0:")
print(replaced)
Executing the above code produces the following output:
"Replace negative values with 0:" 10 0 20 0 15 0 25 "Replace NA with 0:" 10 0 20 0 30
[ R Language Examples](https://example.com/r/r-examples.html)
YouTip