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.

时间: 2025-01-06 21:59:21

R Programming week2 Control Structures的相关文章

Scala Control Structures

Scala之Control Structures 一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Structures Scala中的控制结构与Java中的颇为类似,但也有所不同,例如,if/then/else控制结构与Java的类似,但是其可以返回值,虽然Java中有三元运算符的特殊语法,但是在Scala中使用if就可以达到同样的效果. val x = if (a) y else z 同样,Scala的

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

完成R Programming第三周 这周作业有点绕,更多地是通过一个缓存逆矩阵的案例,向我们示范[词法作用域 Lexical Scopping]的功效.但是作业里给出的函数有点绕口,花费了我们蛮多心思. Lexical Scopping: The value of free variables are searched for in the environment where the function was defined. 因此 make.power<-function(n){ pow<

【Scala】Scala之Control Structures

一.前言 前面学习了Scala的Numbers,接着学习Scala的Control Structures(控制结构). 二.Control Structures Scala中的控制结构与Java中的颇为类似,但也有所不同,例如,if/then/else控制结构与Java的类似,但是其可以返回值,虽然Java中有三元运算符的特殊语法,但是在Scala中使用if就可以达到同样的效果. val x = if (a) y else z 同样,Scala的try/catch/finally 结构与Java

R Programming week1-Reading Data

Reading Data There are a few principal functions reading data into R. read.table, read.csv, for reading tabular data readLines, for reading lines of a text file source, for reading in R code files (inverse of dump) dget, for reading in R code files (

R Programming week 3-Loop functions

Looping on the Command Line Writing for, while loops is useful when programming but not particularly easy when working interactively on the command line. There are some functions which implement looping to make life easier lapply: Loop over a list an

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

Introduction For this first programming assignment you will write three functions that are meant to interact with dataset that accompanies this assignment. The dataset is contained in a zip file specdata.zip that you can download from the Coursera we

R Programming week1-Data Type

Objects R has five basic or “atomic” classes of objects: character numeric (real numbers) integer complex logical (True/False) The most basic object is a vector A vector can only contain objects of the same class BUT: The one exception is a list, whi

Coursera系列-R Programming (John Hopkins University)-课件案例

课件里介绍了一个很实用又能学到很多知识点的例子.并且Roger老师可是用了40分钟的视频亲力亲为.所以这里我把课件和视频知识整理一下会比较更清晰地解析这个案例. 视频链接: https://www.youtube.com/watch?v=VE-6bQvyfTQ&feature=youtu.be Data Analysis Case Study: Changes in Fine Particle Air Pollution in the U.S. Reading in the 1999 data

R Programming week 3-Debugging

Something’s Wrong! Indications that something’s not right message: A generic notification/diagnostic message produced by the message function;execution of the function continues warning: An indication that something is wrong but not necessarily fatal