【1.2】控制结构

• if, else:测试模中情况
• for: 循环运行
• while: 如果为真就运行
• repeat: 循环运行
• break: 停止运行
• next: 跳出
• return: 回到某个功能更

if循环

if(<>) {
## do something
} else {
## do something else
}

if() {
## do something
} else if() {
## do something different
} else {
## do something different
}

if(x > 3) {
y <- 10
} else {
y <- 0
}

y <- if(x > 3) {
10
} else {
0
}


for循环

 for(i in 1:10) {
print(i)
}

x <- c("a", "b", "c", "d")

for(i in 1:4) {
print(x[i])
}

for(i in <span style="color: #ff0000;">seq_along</span>(x)) {
print(x[i])
}

for(letter in x) {
print(letter)
}

for(i in 1:4) print(x[i])

<strong> 二维for</strong>
x <- matrix(1:6, 2, 3)
for(i in <span style="color: #ff0000;">seq_len(nrow(x))</span>) {
for(j in <span style="color: #ff0000;">seq_len(ncol(x)</span>)) {
print(x[i, j])
}
}


While循环

count <- 0
while(count < 10) {
print(count)
count <- count + 1
}

z <- 5
while(z >= 3 && z <= 10) {
print(z)
coin <- rbinom(1, 1, 0.5)
if(coin == 1) { ## random walk
z <- z + 1
} else {
z <- z - 1
}
}


Repeat循环

停止repeat的方式就是break
x0 <- 1
tol <- 1e-8
repeat {
x1 <- computeEstimate()
if(abs(x1 - x0) < tol) {
break
} else {
x0 <- x1
}
}


next循环

for(i in 1:100) {
if(i <= 20) {
## Skip the first 20 iterations
next
}
## Do something here
}
return signals that a function should exit and return a given value