R ifelse() Function - Vectorized Conditional Judgment

R 语言实例R Language Examples

The R ifelse() function is used to perform element-wise conditional judgment and assignment on vectors.

ifelse() is a vectorized version of if...else, which can process an 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:

  • testLogical condition expression.

  • yesValue returned when the condition is TRUE.

  • noValue returned when the 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/Fail 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:

[1] "及格判断:"
 [1] "及格" "及格" "及格" "及格" "及格" "及格" "及格"
 [8] "及格" "及格" "及格"
[1] "等级判断:"
 [1] "良好" "优秀" "中等" "优秀" "良好" "中等" "优秀"
 [8] "及格" "良好" "良好"

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("Negative values replaced 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("NA replaced with 0:")
print(replaced)

Executing the above code produces the following output:

[1] "负值替换为 0:"
[1] 10  0 20  0 15  0 25
[1] "NA 替换为 0:"
[1] 10  0 20  0 30

R 语言实例R Language Examples

Other Extensions