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. struts2的一些小问题

    1.action和ValueStack的关系2.ValueStack的类set()方法和setValue()方法的区别3.ValueStack的类push()方法的作用4.从ValueStack对象中 ...

  2. HDU1054 Strategic Game —— 最小点覆盖 or 树形DP

    题目链接:https://vjudge.net/problem/HDU-1054 Strategic Game Time Limit: 20000/10000 MS (Java/Others)     ...

  3. android NDK 使用(多个)静态库生成动态库

    android NDK 使用(多个)静态库生成动态库. 1.编写Android.mk文件:如下两种方式都可以,用于NDK编译工具生成的两个.a文件来生成最终的libtwolib-second.so动态 ...

  4. ACTION 中 单表查询语句 SQL写法

    JSP页面 <tr> <td class="STYLE1"> <div align="center"> // 单击事件 调用 ...

  5. 【转】WdatePicker.js的使用方法 帮助文档 使用说明 如何使用

    [转]WdatePicker.js的使用方法 帮助文档 使用说明 如何使用 日期控件支持平面显示功能,只要设置一下eCont属性就可以把它当作日历来使用了,无需触发条件,直接显示在页面上 示例2-1 ...

  6. idea如何将普通文件夹转成java项目root目录/maven

    转java项目 转maven 选中pom文件右键就能看到了

  7. 网络抓包工具wireshark and tcpdump 及其实现基于的libpcap

    最近无意中看到博客园中一篇介绍wireshark的文章,写得不错,它简单清楚介绍了wireshark的使用 简介 wireshark以前叫做Ethereal, 在大学时候的网络课程中就常看到它,它是世 ...

  8. 优化Laravel的分页LIMIT和OFFSET调用

    在分页系统中使用limit和offset是很常见的,它们通常也会和ORDER BY一起使用.索引对排序较有帮助,如果没有索引就需要大量的文件排序. 一个常见的问题是偏移量很大,比如查询使用了LIMIT ...

  9. Entity Framework Code First 迁移

    Entity Framework CodeFirst数据迁移 http://www.cnblogs.com/aehyok/p/3325459.html Entity Framework Code Fi ...

  10. [App Store Connect帮助]八、维护您的 App(3)将 App 恢复至 App Store

    如果您已将 App 从 App Store 中移除,之后创建了该 App 的一个新版本,那么即使新版本被“App 审核”批准,App 状态也仍会是“被开发者下架”.若要发布新版本,您必须首先将其恢复至 ...