
1.3.1 if分支
if分支也被称作条件语句,主要用来判断相应条件下的代码执行内容,具体语法如下:

如果if后的条件判断为真,则执行statements对应的语句,否则执行alternative statements对应的语句。if后的判断条件可以是逻辑型向量,也可以是数值型向量。当判断条件为数值型向量时,0代表条件为假,其余数值代表条件为真。根据下面的代码,由于x的值为6,x大于0,条件判断为真,因此输出结果为"Positive number"。

根据下面的代码,由于x1的值为6,条件判断为假,因此输出结果为"Negative number"。

需要注意的是,else必须与if语句的右大括号写在同一行。上述代码也可以写成单独的一行,得到的输出结果一致。

R语言的特性允许我们按以下结构编写代码:

当有多个条件需要判断时,可以重复编写if…else…if…语句,语法如下:

不管有多少个判断条件,最终只有一个条件满足要求,也只有该条件下的语句会被执行。由于x4的取值为0,因此它只符合else中的条件,故而执行结果为“Zero”。

向量构成了R语言的基本组成部分,R语言中的大多数函数都将向量作为输入和输出,这种代码向量化的方式比单独将相同的函数应用于向量的每个元素要快得多。与此概念类似,R语言中的if…else语句有一个向量等价形式,即 ifelse()函数。ifelse()函数的语法为:

其中cond是判断条件,当判断条件为真时,输出statement1的值,否则输出statement2的值,示例如下:

ifelse()函数的输入向量x5中包含6个元素,需要判断这些元素的奇偶性。若其对2求余的结果为0,则说明其为偶数,否则为奇数。
在上述例子中,判断条件为x5%%2==0,这将导致结果向量(FALSE,TRUE, FALSE, FALSE,TRUE, FALSE),该向量对应到输出语句后才转换成了我们看到的结果。