








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
R Studio Programing R Studio Programing R Studio Programing R Studio Programing
Typology: Thesis
1 / 14
This page cannot be seen from the preview
Don't miss anything!









2 /
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.
4 /
This is a valid if/else structure. So is this one. if(x > 3 ) { y <- 10 } else { y <- 0 } y <- if(x > 3 ) { 10 } else { 0 }
5 /
Of course, the else clause is not necessary. if(
7 /
These three 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])
8 /
for loops can be nested. Be careful with nesting though. Nesting beyond 2–3 levels is often very difficult to read/understand. x <- matrix( 1 : 6 , 2 , 3 ) for(i in seq_len(nrow(x))) { for(j in seq_len(ncol (x))) { print(x[i, j]) } }
10/
Sometimes there will be more than one condition in the test. Conditions are always evaluated from left to right. 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 } }
11 /
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. x 0 <- 1 tol <- 1e- repeat { x 1 <- computeEstimate() if(abs(x 1 - x0) < tol) { break } else { x 0 <- x } }
13 /
next is used to skip an iteration of a loop return signals that a function should exit and return a given value for(i in 1 : 100 ) { if(i <= 20 ) {
iterations next }
}
14 /
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.