Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R ifelse() Function - Vectorized Conditional Judgment

R ifelse() Function - Vectorized Conditional Judgment

R Language Examples R Language Examples

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:

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"

)

print

(

"Pass/fail judgment:"

)

print

(

result

)

Multi-level judgment (nested ifelse)

grade

<-

ifelse

(

scores

=

90

,

"Excellent"

,

         

ifelse

(

scores

=

80

,

"Good"

,

         

ifelse

(

scores

=

70

,

"Medium"

,

         

ifelse

(

scores

=

60

,

"Pass"

,

"Fail"

)

)

)

)

print

(

"Grade judgment:"

)

print

(

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

)

print

(

"Negative values replaced with 0:"

)

print

(

cleaned

)

Replace missing values

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

)

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 R Language Examples