R(09):第二章:2.8控制流

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/genome_denovo/article/details/82291246

《统计建模与R软件》薛毅

第2章 R软件的使用

总结:分支结构if语句,if/else语句,条件成立执行if语句不成立则执行else语句;分支结构switch语句switch(statement, list),statement为数字,执行list当中的第几条语句;break终止,next跳过;循环语句for, while, repeat,for语句for (name in expr1) expr2,name在expr1中执行expr2,否则退出;while (condition) expo,condition条件成立执行expo,否则退出;repeat循环语句中执行if语句,if语句成立则执行break语句并退出,原理和while语句相同。

2.8 控制流

2.8.1 分支语句

分支语句包括if / else语句,switch语句。

1. if / else 语句

if / else 语句的格式为:
if(cond) statement_1
if(cond) statement_1 else statement_2
第一句的意义是:如果条件cond成立,则执行表达式statement_1;否则跳过。第二句的意义是:如果条件cond成立,则执行表达式statement_1;否则执行表达式statement_2。
例如:
> x=10
> if(any(x<=0)) y<-log(1+x) else y<-log(x); y #cond语句为x<=0判断时不成立,则执行y<-log(x),y的值为2.302585
[1] 2.302585
> x=0
> if(any(x<=0)) y<-log(1+x) else y<-log(x); y #cond语句为x<=0判断时成立,则执行y<-log(1+x),y的值为0
[1] 0
请注意:次命令与下面的命令等价
> y <- if(any(x<=0)) log(1+x) else log(x)
对于if / else语句,还有下面的用法:
if (cond_1)
····statement_1
else if (cond_2)
····statement_2
else if (cond_3)
····statement_3
else
····statement_4

2. switch语句

switch语句是多分支语句,其用法为:
switch(statement, list)
其中statement是表达式,list是列表,可以用有名定义。如果表达式的返回值在1到length(list),则返回列表相应位置的值;否则返回NULL值,例如:
> x <- 1
> switch(x, 2+2, mean(1:10), c(6,7,8,9))
[1] 4
> switch(2, 2+2, mean(1:10), c(6,7,8,9))
[1] 5.5
> switch(3, 2+2, mean(1:10), c(6,7,8,9))
[1] 6 7 8 9
> switch(4, 2+2, mean(1:10), c(6,7,8,9))
其中list表示上面式子中的2+2, mean(1:10), c(6,7,8,9)而他们的下标分别是1,2,3当x为1时选择2+2,当x为2时选择mean(1:10),当x为3时选择c(6,7,8,9)。
当list时有名定义时,statement等于变量名时,返回变量名对应的值;否则,返回NULL值,例如:
> y <- 'fruit'
> switch(y, fruit='banana', vegetable='broccoli', meat='beef')
[1] "banana"

2.8.2 中止语句与空语句

中止语句是break语句,break语句的作用是中止循环,使程序跳出循环外。空语句是next语句,next语句是继续执行,而不执行某个实质性的内容。

2.8.3 循环语句

循环语句有for循环、while循环和repeat循环语句。

1. for循环语句

for循环的格式为:
for (name in expr_1) expr_2
其中name是循环变量,expr_1是一个向量表达式(通常是个序列,如1:20),expr_2通常是一组表达式。
例如,构造一个4阶的Hilbert矩阵,
> n<-4; x<-array(0,dim=c(n,n))
> x
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
[3,] 0 0 0 0
[4,] 0 0 0 0
> for (i in 1:n){for (j in 1:n){x[i, j] <- 1/(i+j-1)} }
> x
[,1] [,2] [,3] [,4]
[1,] 1.0000000 0.5000000 0.3333333 0.2500000
[2,] 0.5000000 0.3333333 0.2500000 0.2000000
[3,] 0.3333333 0.2500000 0.2000000 0.1666667
[4,] 0.2500000 0.2000000 0.1666667 0.1428571

2. while循环语句

while循环语句的格式为:
> while (condition) expo
若条件condition成立,则执行表达式expr,例如,用while循环编写一个计算1000以内的Fibonacci数的程序:
> f<-1; f[2]<-1; i<-1
> f
[1] 1 1
> while (f[i]+f[i+1]<1000) {f[i+2]<-f[i]+f[i+1]; i<-i+1}
> f
[1] 1 1 2 3 5 8 13 21 34 55 89 144 233 377
[15] 610 987

3. repeat循环语句

repeat循环依赖break语句跳出循环,(相当于将while循环中的condition语句作为break的条件)。例如,用repeat循环编写一个计算1000以内的Fibonacci数的程序。
> f<-1; f[2]<-1; i<-1
> f
[1] 1 1
> repeat {f[i+2]<-f[i]+f[i+1]; i<-I+1; if (f[i]+f[i+1]>=1000) break}
> f
[1] 1 1 2 3 5 8 13 21 34 55 89 144 233 377
[15] 610 987
或将条件语句改为if (f[i]+f[i+1]<1000) next else break,会得到同样的计算结果。

猜你喜欢

转载自blog.csdn.net/genome_denovo/article/details/82291246
今日推荐