循環(生成斐波那契數列為例)
for 循環
d[1] = 1 d[2] = 1 for(i in 3:20){ d[i] = d[i-1]+d[i-2] print(d[i])}
while 循環
e = rep(0, 10) e[1] = 1 e[2] = 1 i = 3 while (i<=10){ e[i] = e[i-1] + e[i-2] i=i+1 } print(e)
條件控制流
條件表達式
if(條件) 表達式
if(條件1) 表達式1 else 表達式2
if(條件1) 表達式1 else if (條件i) 表達式i…… else 表達式
f = c(1,2,3,4,5,1,2,6,11) g = c() for(i in 1:length(f))
# 條件語句 { if(f[i]==1) g[i]="a" else if(f[i]==2) g[i]="b" else g[i]="c" }
自定義函數
h = function(a=1,b=2) # a, b 關鍵字參數 {x = seq(-1,1, 0.2) # 生成等差數列 y = a*x + b plot(x,y)} # 畫圖 h() h(3,4)