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. github相关

    1 某次release的源码 某次release的源码在release列表中,不在branch中,tag和release是在一起的.所以,下载某个release的源码应该去release中找,而不应该 ...

  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. 两大数相乘 -- javascript 实现

    (function (){ var addLarge = function(n1,n2){ var carry = 0; var ret = ""; n1=n1.toString( ...

  4. caioj1230: [图论补充]哈密顿路径

    保存模版 #include<cstdio> #include<iostream> #include<cstring> #include<cstdlib> ...

  5. 并不对劲的bzoj4817:loj2001:p3703:[SDOI2017]树点涂色

    题目大意 有一棵\(n\)(\(n\leq10^5\))个节点的树,每个点有颜色\(c\),一开始所有颜色互不相同 要进行\(m\)(\(m\leq10^5\))次操作,每次操作是以下三种中的一种: ...

  6. redis启动时指定配置文件

    Redis 启动时指定配置文件需要通过 redis 服务启动才行: 安装服务的教程:http://blog.csdn.net/justinytsoft/article/details/54580919 ...

  7. 小程序-demo:小程序示例-page/component

    ylbtech-小程序-demo:小程序示例-page/component 以下将展示小程序官方组件能力,组件样式仅供参考,开发者可根据自身需求自定义组件样式,具体属性参数详见小程序开发文档. 1. ...

  8. "cannot be resolved or is not a field"问题解决 (转载)

    转自:http://blog.csdn.net/liranke/article/details/16803295 在修改了资源文件后,出现“"cannot be resolved or is ...

  9. svn报错:privious operation has not finshed;run 'cleanup' if it was interrupted

    在更新svn的过程中,可能中途会取消,取消之后再次更新时可能提示,如下图: 下载sqlite3工具,进入此下载地址:https://www.sqlite.org/download.html 将sqli ...

  10. 洛谷 P4552 [Poetize6] IncDec Sequence【差分+脑洞】

    一看区间操作,很容易想到差分 所以就是先差分,然后为了保证最小步数,把政府差分抵消,也就相当于原数组区间加减 第二问,因为差分数组抵消之后不为0就需要使用n+1的虚拟位置,而这个的值其实没有,所以我们 ...