How to use the ifelse statement in R language?

In R language, the ifelse statement is a conditional vectorized function used to perform different operations on each element of a vector or data frame based on logical conditions.

The basic syntax of the if-else statement is as follows:

If the condition is true, return the true value; otherwise, return the false value.

In this case,

  1. Condition is a logical condition that can be a logical vector, logical expression, or logical function.
  2. The true_value is the value returned when the condition is TRUE.
  3. The false_value is the value returned when the condition is FALSE.

If the condition is TRUE, ifelse will return true_value; if the condition is FALSE, it will return false_value. Ifelse can handle multiple elements at once, making it ideal for performing conditional checks and transformations in vectors or data frames.

Here are some examples:

# 示例1:根据性别向量生成一个新的性别标签向量
gender <- c("M", "F", "F", "M", "M", "F")
gender_label <- ifelse(gender == "M", "Male", "Female")
# 结果: "Male" "Female" "Female" "Male" "Male" "Female"

# 示例2:根据分数向量生成一个新的及格标签向量
scores <- c(80, 65, 90, 75, 50, 85)
pass_label <- ifelse(scores >= 60, "Pass", "Fail")
# 结果: "Pass" "Pass" "Pass" "Pass" "Fail" "Pass"

# 示例3:根据年龄向量生成一个新的年龄段标签向量
ages <- c(18, 25, 40, 60, 30, 50)
age_label <- ifelse(ages < 30, "Young", ifelse(ages < 50, "Middle-aged", "Old"))
# 结果: "Young" "Young" "Middle-aged" "Old" "Middle-aged" "Old"

It is important to note that ifelse statements may be slower when working with large datasets because they are element-wise operations. If dealing with large data frames or matrices, consider using more efficient vectorized functions like logical indexing, the mutate function in the dplyr package, etc.

bannerAds