R ifelse() Function - Vectorized Conditional Judgment
The R ifelse() function is used to perform element-wise conditional judgment and assignment on a vector.
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:
-
test A logical condition expression.
-
yes The value returned when the condition is TRUE.
-
no The value returned when the condition is FALSE.
Example
scores
<-
c
(
85
,
92
,
78
,
95
,
88
,
72
,
90
,
68
,
82
,
89
)
Use ifelse to judge whether a score is passing
result
<-
ifelse
(
scores
=
60
,
"Pass"
,
"Fail"
)
(
"Pass/fail judgment:"
)
(
result
)
Multi-level judgment (nested ifelse)
grade
<-
ifelse
(
scores
=
90
,
"Excellent"
,
ifelse
(
scores
=
80
,
"Good"
,
ifelse
(
scores
=
70
,
"Medium"
,
ifelse
(
scores
=
60
,
"Pass"
,
"Fail"
)
)
)
)
(
"Grade judgment:"
)
(
grade
)
The output of the code above is:
[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
)
(
"Negative values replaced with 0:"
)
(
cleaned
)
Replace missing values
data_with_na
<-
c
(
10
, NA,
20
, NA,
30
)
replaced
<-
ifelse
(
is.na
(
data_with_na
)
,
0
, data_with_na
)
(
"NA replaced with 0:"
)
(
replaced
)
The output of the code above is:
[1] "负值替换为 0:"
[1] 10 0 20 0 15 0 25
[1] "NA 替换为 0:"
[1] 10 0 20 0 30
R Language Examples