【1.5.1】控制结构

控制结构程序运行的顺序,一般包括:

  • 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

参考资料:

内容来自于Roger D. Peng的《Computing for Data Analysis》

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn