本节书摘来自华章社区《R语言机器学习:实用案例分析》一书中的第1章,第1.4节控制代码流,作者[印度] 拉格哈夫·巴利(Raghav Bali)迪潘简·撒卡尔(Dipanjan Sarkar),更多章节内容可以访问云栖社区“华章社区”公众号查看
1.4 控制代码流
本节讨论如何控制代码的执行。使用特定的结构,例如 if-else 和 switch ,你可以有
条件地执行代码。像 for 、 while 、 repeat 和 help 这样的结构用于多次执行同样的代码,也
称作循环结构。下面我们将研究所有这些结构。
1.4.1 使用 if、if-else 和 ifelse 语句
有几个结构可以帮助我们按照不同的条件来执行代码。当我们不想按顺序依次执行一
系列语句,而是在满足特定条件或不满足特定条件时执行,这种结构是十分有用的。下面
的例子将进行说明:
Controlling code flow
This section covers areas related to controlling the execution of your code. Using
specific constructs such as if-else and switch , you can execute code conditionally.
Constructs like for , while , and repeat , and help in executing the same code
multiple times which is also known as looping. We will be exploring all these
constructs in the following section.
Working with if, if-else, and ifelse
There are several constructs which help us in executing code conditionally. This is
especially useful when we don't want to execute a bunch of statements one after the
other sequentially but execute the code only when it meets or does not meet specific
conditions. The following examples illustrate the same:
> num = 5
> if (num == 5){
+ cat('The number was 5')
+ }
The number was 5
>
> num = 7
>
> if (num == 5){
+ cat('The number was 5')
+ } else{
+ cat('The number was not 5')
+ }
The number was not 5
>
> if (num == 5){
+ cat('The number was 5')
+ } else if (num == 7){
+ cat('The number was 7')
+ } else{
+ cat('No match found')
+ }
Getting Started with R and Machine Learning
[ 30 ]
The number was 7
> ifelse(num == 5, "Number was 5", "Number was not 5")
[1] "Number was not 5"
Working with switch
The switch function is especially useful when you have to match an expression or
argument to several conditions and execute only if there is a specific match. This
becomes extremely messy when implemented with the if-else constructs but is
much more elegant with the switch function, as we will see next:
> switch(
+ "first",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "1st"
>
> switch(
+ "third",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "3rd"
> # when no match, default statement executes
> switch(
+ "fifth",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "No position"
1.4.2 使用 switch 语句
当你必须将一个表达式或参数与多个条件进行匹配时,并且如果只存在一个特定的匹
配才执行语句时, switch 函数是十分有用的。当使用 if-else 结构实现时这将变得十分复
杂,但使用 switch 函数将变得十分简洁,如下所示:
Getting Started with R and Machine Learning
[ 30 ]
The number was 7
> ifelse(num == 5, "Number was 5", "Number was not 5")
[1] "Number was not 5"
Working with switch
The switch function is especially useful when you have to match an expression or
argument to several conditions and execute only if there is a specific match. This
becomes extremely messy when implemented with the if-else constructs but is
much more elegant with the switch function, as we will see next:
> switch(
+ "first",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "1st"
>
> switch(
+ "third",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "3rd"
> # when no match, default statement executes
> switch(
+ "fifth",
+ first = "1st",
+ second = "2nd",
+ third = "3rd",
+ "No position"
+ )
[1] "No position"
1.4.3 循环
当需要时,循环是重复执行代码片段十分有效的方法。然而,在本章的之后章节中,
我们将看到在处理更大的数据集时,向量化结构比循环更优化。现在,你应该记住在 R 中
有 3 种类型的循环: for 、 while 和 repeat 。在下面的例子中我们将讨论它们:
Chapter 1
[ 31 ]
Loops
Loops are an excellent way to execute code segments repeatedly when needed.
Vectorization constructs are, however, more optimized than loops for working
on larger data sets, but we will see that later in this chapter. For now, you should
remember that there are three types of loops in R, namely, for , while , and repeat .
We will look at all of them in the following examples:
> # for loop
> for (i in 1:10){
+ cat(paste(i," "))
+ }
1 2 3 4 5 6 7 8 9 10
>
> sum = 0
> for (i in 1:10){
+ sum <- sum + i
+ }
> sum
[1] 55
>
> # while loop
> count <- 1
> while (count <= 10){
+ cat(paste(count, " "))
+ count <- count + 1
+ }
1 2 3 4 5 6 7 8 9 10
>
> # repeat infinite loop
> count = 1
> repeat{
+ cat(paste(count, " "))
+ if (count >= 10){
+ break # break off from the infinite loop
+ }
Getting Started with R and Machine Learning
+ count <- count + 1
+ }
1 2 3 4 5 6 7 8 9 10