条件
if_else
if (cond) statement_1
if (cond) statement_1 else statement_2
if (cond_1)
statement_1
else if (cond_2)
statement_2
else if (cond_3)
statement_3
else
statement_4
switch 语句
switch(statement, list)
如果表达式的返回值在 1到 lenght(list),则返回列表相应位置的值;否则返回“NULL”
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))
中止语句与空语句
break
break
中止循环,使程序跳到循环以外
next
next
语句是继续执行,而不执行某个实质性的内容
循环
for
构造4阶 Hilbert 矩阵
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;
while
当条件 condition 成立,则执行表达式 expr
while (condition) expr
例:用 while 编写一个计算1000以内的 Fibonacci 数
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;
repeat
repeat
循环依赖 break
语句跳出循环
例:用 repeat 编写一个计算1000以内的 Fibonacci 数
f <- 1;
f[2] <- 1;
i <- 1;
repeat{
f[i+2] <- f[i] + f[i+1];
i <- i+1;
if (f[i]+f[i+1]>=1000) break
}
f;