在R中可以使用函数dplyr中提供的case_when函数来代替嵌套ifelse语句。下面是一个示例:
library(dplyr)
# 嵌套ifelse语句
score <- 71
grade <- ifelse(score >= 90, "A",
ifelse(score >= 80, "B",
ifelse(score >= 70, "C", "D")))
print(grade) # 输出 "C"
# 使用case_when函数
score <- 71
grade <- case_when(score >= 90 ~ "A",
score >= 80 ~ "B",
score >= 70 ~ "C",
TRUE ~ "D")
print(grade) # 输出 "C"
通过上述示例,我们可以看到在使用case_when函数时,语句更加清晰简洁,比嵌套ifelse语句更易读且不易出错。
上一篇:避免在R中使用嵌套的for循环
下一篇:避免在R中修剪图形中的曲线。