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.

R Programming week2 Control Structures的更多相关文章

  1. R Programming week2 Functions and Scoping Rules

    A Diversion on Binding Values to Symbol When R tries to bind a value to a symbol,it searches through ...

  2. Coursera系列-R Programming第二周

    博客总目录,记录学习R与数据分析的一切:http://www.cnblogs.com/weibaar/p/4507801.html  --- 好久没发博客 且容我大吼一句 终于做完这周R Progra ...

  3. Python - 4. Control Structures

    From:http://interactivepython.org/courselib/static/pythonds/Introduction/ControlStructures.html Cont ...

  4. Coursera系列-R Programming第三周-词法作用域

    完成R Programming第三周 这周作业有点绕,更多地是通过一个缓存逆矩阵的案例,向我们示范[词法作用域 Lexical Scopping]的功效.但是作业里给出的函数有点绕口,花费了我们蛮多心 ...

  5. 让reddit/r/programming炸锅的一个帖子,还是挺有意思的

    这是原帖 http://www.reddit.com/r/programming/comments/358tnp/five_programming_problems_every_software_en ...

  6. 【Scala】Scala之Control Structures

    一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Structures Scala中的控制结构与Java中的颇 ...

  7. Scala Control Structures

    Scala之Control Structures 一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Struc ...

  8. [R] [Johns Hopkins] R Programming 作業 Week 2 - Air Pollution

    Introduction For this first programming assignment you will write three functions that are meant to ...

  9. R Programming week 3-Loop functions

    Looping on the Command Line Writing for, while loops is useful when programming but not particularly ...

随机推荐

  1. 【iOS系列】-oc中的集合类

    OC中的集合有:NSArray 数组 NSDictionary 字典 NSSet 集合 第一:NSArrary 1.1:集合的基本方法 //1.创建集合 //NSArray 是不可变数组,一旦创建完成 ...

  2. JS文件中引用另一个JS文件

    1.生产项目上遇到一个Bug,需要修改JS文件,添加Jquery代码,但是原来的页面没有添加对Jquery文件的引用,无法修改原来的页面(自动生成的HTML) 这就需要在JS文件中添加对Jquery文 ...

  3. CMMI Institute Conference 2014中国大会

    我在大会上做SPD(Strategic Policy Deployment战略部署策略)的演讲,和来自各个公司的高管进行了热烈的讨论.获得好评. 有兴趣的朋友能够点击下面链接:Stratehttp:/ ...

  4. YTU 1076: SPY

    1076: SPY 时间限制: 1 Sec  内存限制: 128 MB 提交: 6  解决: 6 题目描述 The National Intelligence Council of X Nation ...

  5. python 列表,元祖,字典

    一 列表 1 列表的循环遍历 namesList = ['xiaoWang','xiaoZhang','xiaoHua'] for name in namesList: print(name) 结果 ...

  6. 洛谷 P2444 [ POI 2000 ] 病毒 —— AC自动机+dfs

    题目:https://www.luogu.org/problemnew/show/P2444 AC自动机上 dfs,不走结尾点,如果走出环就是有无限长度的串: RE无数,原来是数组开成 2000 的了 ...

  7. 无参数的lambda匿名函数

    lambda 语法: lambda [arg1[,arg2,arg3....argN]]:expression 1.单个参数的: g = lambda x:x*2 print g(3) 结果是6 2. ...

  8. webpack -v显示的版本与package.json的devDependencies节点显示的webpack版本不一致的问题

    最近在学习webpack,遇到个奇葩的问题.就是安装完成webpack后,查看安装的webpack版本与package.json中显示的版本不一致, webpack是局部安装的,非全局安装, 命令1: ...

  9. 计蒜课--2n皇后、n皇后的解法(一般操作hhh)

    给定一个 n*nn∗n 的棋盘,棋盘中有一些位置不能放皇后.现在要向棋盘中放入 nn 个黑皇后和 nn个白皇后,使任意的两个黑皇后都不在同一行.同一列或同一条斜线(包括正负斜线)上,任意的两个白皇后都 ...

  10. Vue父子组件传值之——访问根组件$root、$parent、$children和$refs

    Vue组件传值除了prop和$emit,我们还可以直接获取组件对象: 根组件: $root // 单一对象 表示当前组件树的根 Vue 实例,即new Vue({...根组件内容}).如果当前实例没有 ...