R Programming week2 Control Structures
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的更多相关文章
- 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 ...
- Coursera系列-R Programming第二周
博客总目录,记录学习R与数据分析的一切:http://www.cnblogs.com/weibaar/p/4507801.html --- 好久没发博客 且容我大吼一句 终于做完这周R Progra ...
- Python - 4. Control Structures
From:http://interactivepython.org/courselib/static/pythonds/Introduction/ControlStructures.html Cont ...
- Coursera系列-R Programming第三周-词法作用域
完成R Programming第三周 这周作业有点绕,更多地是通过一个缓存逆矩阵的案例,向我们示范[词法作用域 Lexical Scopping]的功效.但是作业里给出的函数有点绕口,花费了我们蛮多心 ...
- 让reddit/r/programming炸锅的一个帖子,还是挺有意思的
这是原帖 http://www.reddit.com/r/programming/comments/358tnp/five_programming_problems_every_software_en ...
- 【Scala】Scala之Control Structures
一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Structures Scala中的控制结构与Java中的颇 ...
- Scala Control Structures
Scala之Control Structures 一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Struc ...
- [R] [Johns Hopkins] R Programming 作業 Week 2 - Air Pollution
Introduction For this first programming assignment you will write three functions that are meant to ...
- R Programming week 3-Loop functions
Looping on the Command Line Writing for, while loops is useful when programming but not particularly ...
随机推荐
- iOS 配置支付宝
尽管非常easy,可是对于第一次接触支付宝配置的啊猿.有些细节摸不着头脑.今天就来写一个流程配置. 1.创建一个project,然后再创建一个目录,把支付宝sdk要用到的都拖到目录中.然后拖到proj ...
- SQL Server中一些有用的日期sql语句
SQL Server中一些有用的日期sql语句 1.一个月第一天的 SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) 2.本周的星期一 SELECT DA ...
- 安装mint的问题集锦
1.修改DNS解析配置 刚刚安装完mint可能现无法连接源的问题,总是说dns解析错误,这个可能是dns配置文件造成的,因为官网下的mint很可能是配置了国外的dns解析,比如我刚安上时,就是默认配置 ...
- 【剑指offer】面试题42:单词翻转顺序&左右旋转字符串
这里尽可能的不去用语言本身提供的函数. 将string逆置 def reverse(string): #return string[::-1] reversedStr = '' for i in xr ...
- 常用的机器学习&数据挖掘知识点总结
Basis(基础): MSE(Mean Square Error 均方误差),LMS(LeastMean Square 最小均方),LSM(Least Square Methods 最小二乘法),ML ...
- Package vim is not available, but is referred to by another package及我的vim配置
新安装的ubuntu,先安装vim,但是安装出现 Reading package lists... Done Building dependency tree Reading state inform ...
- java中abstract和interface的區別(轉)
(一)概述 在Java语言中, abstract class 和interface 是支持抽象类定义的两种机制.正是由于这两种机制的存 在,才赋予了Java强大的 面向对象能力.abstract ...
- Expression Blend实例中文教程(8) - 动画设计快速入门StoryBoard http://silverlightchina.net/html/tips/2010/0329/934.html
Expression Blend实例中文教程(8) - 动画设计快速入门StoryBoard 时间:2010-03-29 11:13来源:SilverlightChina.Net 作者:jv9 点击: ...
- svn回到历史的某个版本
svn回到历史的某个版本 分类: linux大类2011-08-05 10:25 7468人阅读 评论(0) 收藏 举报 svntortoisesvn svn回到历史的某个版本在代码的编写过程中,难免 ...
- [USACO16JAN]愤怒的奶牛Angry Cows
传送门 一道神奇的DP………(鬼知道他为什么在tarjan里面) 一开始可能会考虑贪心或者什么其他神奇的算法,不过还是DP比较靠谱. 我们用f[i]表示摧毁所有i左侧的炸 药包最少需要的能量,用g[i ...