- 20151005 [Coursera] R Programming (7)
- 整理自 R Programming (Week 2) -- Control Structures
- [ Week 2 課程內容 ]
- [ 筆記內容 ]
- [ 補充資料 ]
- < 控制結構 > Introduction
- [ 重點整理 ] 常用的結構
- (一)If-else
- [ 重點整理 ]
- [ 操作範例 ] 利用 if-else 指定y值
- (二)For loops
- [ 重點整理 ]
- (三)While loops
- [ 重點整理 ]
- (四)Repeat loops、 Next、 Break
- [ 重點整理 ]
- 1. Repeat
- 2. Next、Return
Visible to members of this folder
整理自 R Programming (Week 2) -- Control Structures
< 控制結構 > Introduction
(一)If-else
if(condition_1) {
## do A
} else {
## do B
}
if(condition_1) {
## do A
} else if(condition_2) {
## do B
} else {
## do C
}
if(x > 3) {
y <- 10
} else {
y <- 0
}
y <- if(x > 3) {
10
} else {
0
}
(二)For loops
for(i in 1:10) { # 執行的次數;i 從 1 執行到 10 ,總計 10 次。
print(i) # 在每一次執行 for迴圈 時都會列印變數 i 的值。
}
x <- c("a", "b", "c", "d")
for(i in 1:4) {
print(x[i])
}
x <- c("a", "b", "c", "d")
for(i in seq_along(x)) {
print(x[i])
}
x <- c("a", "b", "c", "d")
for(letter in x) {
print(letter)
}
x <- c("a", "b", "c", "d")
for(i in 1:4) print(x[i])
# 列印二維矩陣
x <- matrix(1:6, 2, 3)
for(i in seq_len(nrow(x))) {
for(j in seq_len(ncol(x))) {
print(x[i, j])
}
}
(三)While loops
# 每次進入迴圈前會判斷"count是否小於10",如果符合就會一直執行迴圈內的程式。
count <- 0
while(count < 10) {
print(count)
count <- count + 1
}
z <- 5
while(z >= 3 && z <= 10) { # 當 z大於等於3 以及 z小於等於10 時
print(z)
coin <- rbinom(1, 1, 0.5)
if(coin == 1) {
z <- z + 1
} else {
z <- z - 1
}
}
(四)Repeat loops、 Next、 Break
x0 <- 1
tol <- 1e-8 # 10的-8次方
repeat {
x1 <- computeEstimate()
if(abs(x1 - x0) < tol) {
break # 跳脫"repeat"迴圈
} else {
x0 <- x1
}
}
# 當 i <= 20,都不會執行"程式碼A"
for(i in 1:100) {
if(i <= 20) { # 跳過前20次的迴圈執行
next # 先跳脫這一次執行的迴圈,直接執行下一次
}
# 程式碼A
}