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. 2016/2/25 1、<表单验证<form></form> 2、正则表达式 3、事件

    1.<表单验证<form></form> (1).非空验证(去空格) (2).对比验证(跟一个值对比) (3).范围验证(根据一个范围进行判断) (4).固定格式验证:电 ...

  2. Why Do Microservices Need an API Gateway?

    Why Do Microservices Need an API Gateway? - DZone Integration https://dzone.com/articles/why-do-micr ...

  3. (15)ServletConfig对象详解

    1,作用 主要是用于加载servlet的初始化参数.在一个web应用可以存在多个ServletConfig对象(一个Servlet对应一个ServletConfig对象) 2,创建时机和对象的获取 创 ...

  4. 7-39 Math对象

    7-39 Math对象 学习要点 掌握常用的数学计算方法 温馨提示:关于学习方法的建议 不要强求自己讲参考手册上所以的属性和方法都搞清楚,原因如下: 有些属性和方法非常生僻,很少用,甚至经过一段时间后 ...

  5. html5--switch选择结构的优化

    html5--switch选择结构的优化 问题: 使用循环语句判断月份是31天还是30天 两点提示: 使用switch多条件判断语句 合理的省略break优化代码 <!DOCTYPE html& ...

  6. I.MX6 Android shutdown shell command

    /******************************************************************************* * I.MX6 Android shu ...

  7. OAuth学习总结

    1.为什么需要OAuth? 新浪微博就是你的家.偶尔你会想让一些人(第三方应用)去你的家里帮你做一些事,或取点东西.你可以复制一把钥匙(用户名和密码)给他们,但这里有三个问题: 1)别人拿了钥匙后可以 ...

  8. bzoj 4571 美味 —— 主席树

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4571 区间找异或值最大,还带加法,可以用主席树: 可以按位考虑,然后通过加上之前已经有的答案 ...

  9. Python+页面元素高亮源码实例

    简单写了一个页面元素高亮的方法,原理就是在python中调用js实现元素高亮,分享一下源码如下: 1.元素高亮源码 Js调用 js = "var q=document.getElementB ...

  10. pybot执行多条用例时,某一个用例执行失败,停止所有用例的执行

    问题: pybot执行多条用例时,某一个用例执行失败,停止所有用例的执行 解决办法: pybot -exitonfailure E:\robot\呼送项目\测试用例\基本流程\主流程.txt 参考文章 ...