使用 if 表达式

由于 if 本质上是一个原函数,它的返回值就是满足条件分支表达式的值,因此,if 表
达式也可以用作内联函数。我们以 check_positive( )为例进行说明。尽管条件表达式
中不另写 return( ) 语句,也可以得到函数体中 if 表达式的返回值,从而达到与包
含 return( ) 同样的效果:
check_positive <- function(x) {
return(if (x > 0) {
1
})
}
事实上,这个表达式可以简化为一行:
check_positive <- function(x) {
return(if (x > 0) 1)
}
由于函数的返回值就是函数体中最后一个表达式的值,所以在这种情况下,我们可以
删掉 return( ) 语句:
check_positive <- function(x) {
if (x > 0) 1
}
同样的原则也适用于 check_sign( ) 函数。一个简单形式如下所示:
check_sign <- function(x) {
if (x > 0) 1 else if (x < 0) -1 else 0
}
为了清楚地理解 if 表达式的值,我们可以编写一个成绩报告函数,给定一个学生的
姓名和分数,该函数就可以报告这个学生的成绩等级:
say_grade <- function(name, score) {
grade <- if (score >= 90) "A"
else if (score >= 80) "B"
else if (score >= 70) "C"
else if (score >= 60) "D"
else "F"
cat("The grade of", name, "is", grade)
}
say_ _grade("Betty", 86)
## The grade of Betty is B
使用 if 语句作为表达式看起来似乎更紧凑、简洁。但在实践中,我们很少遇到所有
条件都是简单的数值比较且最终只需返回一个值的情况。对于更复杂的条件和分支,建议
使用 if 作为一个语句来清楚地声明不同的分支,也不要省略{ },以免不必要错误。下面
的函数就是一个反例:
say_grade <- function(name, score) {
if (score >= 90) grade <- "A"
cat("Congratulations!\n")
else if (score >= 80) grade <- "B"
else if (score >= 70) grade <- "C"
else if (score >= 60) grade <- "D"
else grade <- "F"
cat("What a pity!\n")
cat("The grade of", name, "is", grade)
}
编写这个函数的人本想给各个分支添加说明,但在分支表达式中没有使用 { } 括号,
因此很有可能产生语法错误。如果你在控制台中运行上述代码,产生的错误信息足以让你
困惑一段时间:
>say_grade <- function(name, score) {
+ if (score >= 90) grade <- "A"
+ cat("Congratulations!\n")
+ else if (score >= 80) grade <- "B"
Error: unexpected 'else' in:
" cat("Congratulations!\n")
else"
> else if (score >= 70) grade <- "C"
Error: unexpected 'else' in " else"
> else if (score >= 60) grade <- "D"
Error: unexpected 'else' in " else"
> else grade <- "F"
Error: unexpected 'else' in " else"
> cat("What a pity!\n")
What a pity!
> cat("The grade of", name, "is", grade)
Error in cat("The grade of", name, "is", grade) : object 'name' not found
> }
Error: unexpected '}' in "}"
一种更好的函数形式可以避免这种潜在的陷阱,如下所示:
say_grade <- function(name, score) {
if (score >= 90) {
grade <- "A"
cat("Congratulations!\n")
} else if (score >= 80) {
grade <- "B"
}
else if (score >= 70) {
grade <- "C"
}
else if (score >= 60) {
grade <- "D"
} else {
grade <- "F"
cat("What a pity!\n")
}
cat("The grade of", name, "is", grade)
}
say_ _grade("James", 93)
## Congratulations!
## The grade of James is A
这个函数可能看起来有些繁琐,但它的逻辑更清晰,具备更高的稳健性。记住,正确
总是比简短更重要。

posted @ 2019-01-22 10:50  NAVYSUMMER  阅读(296)  评论(0编辑  收藏  举报
交流群 编程书籍