Control Structures

Control structures in R allow you to control the flow of execution of the program, depending on

runtime conditions. Common structures are:

if, else: testing a condition

for: execute a loop a fixed number of times

while: execute a loop while a condition is true

repeat: execute an infinite loop

break: break the execution of a loop

next: skip an interation of a loop

return: exit a function

Most control structures are not used in interactive sessions, but rather when writing functions or

longer expresisons

Control Structures: if

if(<condition>) { ## do something

} else { ## do something else

}

if(<condition1>) { ## do something

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

} else { ## do something different

}

例:

if(x > 3) {

 y <- 10

} else {

 y <- 0

}

Of course, the else clause is not necessary

if(<condition1>) {

}

if(<condition2>) {

}

for

for loops take an interator variable and assign it successive values from a sequence or vector. For loops are most commonly used for iterating over the elements of an object (list, vector, etc.)

for(i in 1:10) {

 print(i)

}

This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, ..., 10, and then exits.

These following loops have the same behavior:

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

for(i in 1:4) {

 print(x[i])

}

for(i in seq_along(x)) {

 print(x[i])

}

for(letter in x) {

 print(letter)

}

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

Nested for loops

for loops can be nested.

x <- matrix(1:6, 2, 3)

for(i in seq_len(nrow(x))) {

 for(j in seq_len(ncol(x))) {

 print(x[i, j])

 }

}

Be careful with nesting though. Nesting beyond 2–3 levels is often very difficult to read/understand

While

While loops begin by testing a condition. If it is true, then they execute the loop body. Once the loop body is executed, the condition is tested again, and so forth

count <- 0

while(count < 10) {

 print(count)

 count <- count + 1

}

While loops can potentially result in infinite loops if not written properly. Use with care!

Sometimes there will be more than one condition in the test

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

 }

}

Conditions are always evaluated from left to right.

Repeat

Repeat initiates an infinite loop; these are not commonly used in statistical applications but they do have their uses. The only way to exit a repeat loop is to call break.

x0 <- 1

tol <- 1e-8

repeat {

 x1 <- computeEstimate()

 if(abs(x1 - x0) < tol) {

 break

 } else {

 x0 <- x1

 }

}

The loop in the previous slide is a bit dangerous because there’s no guarantee it will stop. Better to set a hard limit on the number of iterations (e.g. using a for loop) and then report whether convergence was achieved or not.

next, return

next is used to skip an iteration of a loop

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

Summary

Control structures like if, while, and for allow you to control the flow of an R program

Infinite loops should generally be avoided, even if they are theoretically correct.

Control structures mentiond here are primarily useful for writing programs; for command-line interactive work, the *apply functions are more useful.

最新文章

  1. OpenCV 学习之路(1)
  2. VC++ 在类中添加多线程操作
  3. 用 eclipse ndk 编译 cocos2d-x for Android
  4. Objective-C设计模式——工厂方法模式virtual constructor(对象创建)
  5. VS2015 Cordova Ionic移动开发(五)
  6. thinkphp 中js 实现刷新
  7. UIKit和Core Graphics绘图(一)——字符串,线条,矩形,渐变
  8. memory引擎的索引失效一例
  9. [Swift]LeetCode961. 重复 N 次的元素 | N-Repeated Element in Size 2N Array
  10. Codeforces 1037C Equalize
  11. GUI Design Studio的使用方法
  12. 玩转BLE(1)_Eddystone beacon
  13. tcp,Socket,三次握手和四次挥手的图示
  14. 解决openoffice进程异常退出的办法
  15. C#什么时候需要使用构造函数
  16. Day6作业及默写
  17. Visual Studio 简单使用常识操作
  18. RabbitMQ(一):Window安装RabbitMQ
  19. 解决还原数据库是出现system.data.sqlclient.sqlerror filestream功能被禁用的问题
  20. HBase目录

热门文章

  1. 关于Address already in use: connect问题分析及解决方案
  2. jquery源码学习笔记三:jQuery工厂剖析
  3. 跨域,Content-Type组件
  4. 将前端js异步调用的多个服务合并为一个前端服务
  5. Windbg脚本和扩展工具开篇
  6. OC:数组排序、时间格式化字符串
  7. linux简单技巧和怎么样进入root用户
  8. bootstrap table 分页后,重新搜索的问题
  9. E20170517-gg
  10. 4800: [Ceoi2015]Ice Hockey World Championship(折半搜索)