while-loop (原本的程式碼)

Brownian <- function(n = 11, pause = 0.05, nIter = 5, ...) {
    x = rnorm(n) 
    y = rnorm(n) 
    i = 1
    while (i <= nIter) {
        plot(x, y, ...)
        text(x, y, cex = 0.5)
        x = x + rnorm(n)
        y = y + rnorm(n)
        Sys.sleep(pause)
        i = i + 1
    }
} 

for-loop (只畫三張)

Brownian <- function(n = 11, pause = 0.05, ...) {
    x = rnorm(n) 
    y = rnorm(n) # rnorm常態分佈的隨機數(mean=0、sd=1)
    i = 1
    for (i in c(1:3)) { # 依序帶入1~3
        plot(x, y, ...) # 畫出x、y
        text(x, y, cex = 0.5) # 標示微粒編號
        x = x + rnorm(n) # 定義x
        y = y + rnorm(n) # 定義y
        Sys.sleep(pause) # 延遲
        i = i + 1 # 定義i
    }
} 

###

## test it (開始繪圖)
Brownian(xlim = c(-20, 20), ylim = c(-20, 20), 
    pch = 21, cex = 2, col = "cyan", bg = "lavender") 

###

repeat-loop (只畫三張)

Brownian <- function(n = 11, pause = 0.05, ...) {
    x = rnorm(n) 
    y = rnorm(n) 
    i = 1
    repeat {
      if(i > 3) break # 重複做,一旦大於3就停止
        plot(x, y, ...)
        text(x, y, cex = 0.5)
        x = x + rnorm(n)
        y = y + rnorm(n)
        Sys.sleep(pause)
        i = i + 1
    }
} 
## test it
Brownian(xlim = c(-20, 20), ylim = c(-20, 20), 
    pch = 21, cex = 2, col = "cyan", bg = "lavender") 

###