2.8 控制流

2.8 控制流

2.8.1 分支语句

1.if/else语句

例如:1

x <- c("what","is","truth")
if("Truth" %in% x){
print("Truth is found")
} else {
print("Truth is not found")
}

例如:

x <- c("what","is","truth")
if("Truth" %in% x){
print("Truth is found the first time")
} else if ("truth" %in% x) {
print("truth is found the second time")
} else {
print("No truth found")
}

2.switch语句

x<-3
switch(x,2+2,mean(1:10),rnorm(4))
switch(2,2+2,mean(1:10),rnorm(4))
switch(6,2+2,mean(1:10),rnorm(4))

2.8 控制流

2.8.2 中止语句与空语句

中止语句break:终止循环是程序跳出循环。

空语句是next语句,next语句是继续执行,而不执行某个实质性内容。

结合循环语句来说明

2.8.3 循环语句

for循环,while循环和repeat循环

1.for循环语句

for(name in expr_1) expr_2

n<-4;x<-array(0,dim=c(n,n))
for(i in 1:n){
for(j in 1:n){
x[i,j]<-1/(i+j-1)
}
};x

2.while

例如:求菲波那契数列小于1000的值

F[n]=F[n-1]+Fn-2

f<-1;f[2]<-1;i=1
while(f[i]+f[i+1]<1000){
f[i+2]<-f[i]+f[i+1];
i<-i+1;
};f

3.repeat

还是求菲波那契数列中小于1000的值

f<-1;f[2]<-1;i=1
repeat{
if(f[i]+f[i+1]>1000) break;
f[i+2]<-f[i]+f[i+1];
i<-i+1;
};f

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容