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