R语言条件语句 #

一、条件语句概述 #

条件语句用于根据条件执行不同的代码块,是控制程序流程的基础。

二、if语句 #

2.1 基本if语句 #

r
x <- 10

if (x > 5) {
  print("x大于5")
}

2.2 if-else语句 #

r
x <- 3

if (x > 5) {
  print("x大于5")
} else {
  print("x不大于5")
}

2.3 if-else if-else语句 #

r
score <- 75

if (score >= 90) {
  print("优秀")
} else if (score >= 80) {
  print("良好")
} else if (score >= 60) {
  print("及格")
} else {
  print("不及格")
}

2.4 单行if语句 #

r
x <- 10

if (x > 5) print("x大于5")

if (x > 5) print("x大于5") else print("x不大于5")

三、ifelse函数 #

3.1 基本用法 #

r
x <- 10

result <- ifelse(x > 5, "大于5", "不大于5")
print(result)

3.2 向量化操作 #

r
x <- c(10, 20, 5, 30, 2)

ifelse(x > 10, "大", "小")

scores <- c(85, 60, 45, 90, 55)
ifelse(scores >= 60, "及格", "不及格")

3.3 嵌套ifelse #

r
scores <- c(95, 85, 75, 65, 55)

grade <- ifelse(scores >= 90, "优秀",
                ifelse(scores >= 80, "良好",
                       ifelse(scores >= 60, "及格", "不及格")))
print(grade)

3.4 处理NA #

r
x <- c(10, NA, 20, NA, 30)

ifelse(is.na(x), "缺失", x)
ifelse(!is.na(x), x * 2, NA)

四、switch函数 #

4.1 数值匹配 #

r
x <- 2

result <- switch(x,
  "选项1",
  "选项2",
  "选项3"
)
print(result)

4.2 字符串匹配 #

r
day <- "Monday"

result <- switch(day,
  "Monday" = "星期一",
  "Tuesday" = "星期二",
  "Wednesday" = "星期三",
  "Thursday" = "星期四",
  "Friday" = "星期五",
  "未知"
)
print(result)

4.3 带默认值 #

r
x <- "unknown"

result <- switch(x,
  "a" = "选项A",
  "b" = "选项B",
  "c" = "选项C",
  "未知选项"
)
print(result)

4.4 执行表达式 #

r
operation <- "add"
a <- 10
b <- 5

result <- switch(operation,
  "add" = a + b,
  "subtract" = a - b,
  "multiply" = a * b,
  "divide" = a / b,
  NA
)
print(result)

五、逻辑运算符组合 #

5.1 与条件 (&) #

r
age <- 25
score <- 85

if (age > 20 & score >= 80) {
  print("符合条件")
}

5.2 或条件 (|) #

r
day <- "Saturday"

if (day == "Saturday" | day == "Sunday") {
  print("周末")
}

5.3 非条件 (!) #

r
is_valid <- FALSE

if (!is_valid) {
  print("数据无效")
}

5.4 复杂条件 #

r
age <- 25
score <- 85
is_member <- TRUE

if ((age > 20 & score >= 80) | is_member) {
  print("符合条件")
}

六、条件语句与向量 #

6.1 遍历向量 #

r
x <- c(10, 20, 30, 40, 50)

for (i in x) {
  if (i > 25) {
    print(paste(i, "大于25"))
  } else {
    print(paste(i, "不大于25"))
  }
}

6.2 筛选向量 #

r
x <- c(10, 20, 30, 40, 50)

result <- x[x > 25]
print(result)

6.3 条件修改 #

r
x <- c(10, 20, 30, 40, 50)

x[x > 30] <- 100
print(x)

七、条件语句与数据框 #

7.1 条件筛选 #

r
df <- data.frame(
  name = c("张三", "李四", "王五"),
  age = c(25, 30, 22),
  score = c(85, 90, 78)
)

df[df$age > 24, ]
df[df$score >= 85, ]

7.2 条件修改 #

r
df <- data.frame(
  name = c("张三", "李四", "王五"),
  score = c(85, 60, 45)
)

df$grade <- ifelse(df$score >= 60, "及格", "不及格")
print(df)

7.3 多条件筛选 #

r
df <- data.frame(
  name = c("张三", "李四", "王五"),
  age = c(25, 30, 22),
  score = c(85, 90, 78)
)

df[df$age > 24 & df$score >= 85, ]

八、最佳实践 #

8.1 使用花括号 #

r
x <- 10

if (x > 5) {
  y <- x * 2
  z <- y + 10
  print(z)
}

8.2 提前返回 #

r
check_positive <- function(x) {
  if (x <= 0) {
    return("非正数")
  }
  return("正数")
}

check_positive(10)
check_positive(-5)

8.3 避免深层嵌套 #

r
process <- function(x) {
  if (is.null(x)) return(NULL)
  if (length(x) == 0) return(NULL)
  if (!is.numeric(x)) return(NULL)
  
  mean(x)
}

8.4 使用向量化操作 #

r
x <- c(10, 20, 30, 40, 50)

result <- ifelse(x > 25, x * 2, x)
print(result)

九、实践示例 #

9.1 成绩等级判断 #

r
get_grade <- function(score) {
  if (score >= 90) {
    return("A")
  } else if (score >= 80) {
    return("B")
  } else if (score >= 70) {
    return("C")
  } else if (score >= 60) {
    return("D")
  } else {
    return("F")
  }
}

get_grade(85)
get_grade(55)

9.2 数据验证 #

r
validate_input <- function(age, score) {
  if (!is.numeric(age) || !is.numeric(score)) {
    stop("输入必须是数值")
  }
  
  if (age < 0 || age > 120) {
    stop("年龄必须在0-120之间")
  }
  
  if (score < 0 || score > 100) {
    stop("分数必须在0-100之间")
  }
  
  TRUE
}

validate_input(25, 85)

9.3 计算器 #

r
calculator <- function(a, b, op) {
  switch(op,
    "+" = a + b,
    "-" = a - b,
    "*" = a * b,
    "/" = if (b != 0) a / b else "除数不能为0",
    "未知操作"
  )
}

calculator(10, 5, "+")
calculator(10, 5, "/")

9.4 分类统计 #

r
categorize <- function(x) {
  ifelse(x < 0, "负数",
         ifelse(x == 0, "零", "正数"))
}

x <- c(-5, 0, 10, -3, 5)
table(categorize(x))

十、总结 #

本章学习了:

  • if语句的基本用法
  • if-else和if-else if-else语句
  • ifelse函数的向量化操作
  • switch函数的条件匹配
  • 逻辑运算符组合条件
  • 条件语句在向量和数据框中的应用
  • 条件语句最佳实践

条件语句是控制程序流程的核心工具,在数据分析中广泛应用!

最后更新:2026-03-27