9 Loops and ifelse statements
9.1 Loops
In programming loops are very common and represent the most basic way to accomplish tasks recursively and or repetitively. We will learn about other ways to handle repetitive operations, but loops are still widely used.
Structure of loops:
for (i in 1:5) # Run the loop by single integers
# start loop
{ # run recursive calculation here
# end loop }
for (i in 1:5)
{print(i)
}
<- 4
n for(i in 1:n)
{print("Hello World")
}
<- 8
n <- c()
n.vect for(i in 1:n)
{<- i + 2
n.vect[i] print(n.vect)
}
Practice
# Use a loop to calculate: 1/2 + 2/3 + 3/4 + 4/5
9.2 Nested Loops
# for (variable in sequence) {
# for (variable in sequence) {
# expression
# }
# }
# Example:
# for(i in 1:n) {
# for(j in 1:n) {
# expression
# }
# }
for (k in 1:3) {
for (l in 1:2) {
print(paste("k =", k, "l= ",l))
} }
= matrix(nrow=4, ncol=4) # create a 4 x 4 matrix (of 4 rows and 4 columns)
res for(i in 1:nrow(res)) { # Assigned a variable ‘i’for each row
for(j in 1:ncol(res)) { # Assigned a variable ‘j for each column
= i*j # calculating product of two indices
res[i,j]
}
}print(res)
9.3 while loop
Syntax of while loop: while (test_expression) { statement }
<- 1
i while (i < 6) {
print(i)
= i+1
i }
9.4 If, else, and ifelse
If statements are useful if we want R to do something based on our logical question.
<- 7
a if (a == 7) print("a is 7")
If the condition is not met, nothing will print to the console
<- 7
a if (a == 5) print("a is 7")
The same approach works if we want to use not logical.
<- 7
a if (a != 5) print("a is not 5")
Using if
and else
together allows you to do one thing if the condition is true and something else if the condition is false.
<- 7
a if (a == 7) print("a is 7") else print("a is not 7")
<- 8
a if (a == 7) print("a is 7") else print("a is not 7")
The if
and else
function only can assess one element at a time. To assess a whole vector, you can use the ifelse
function
<- c(4,3,6,7)
a.vec ifelse(a.vec > 5, "Greater", "Less Than")
Create this data frame in R representing the maximum observed tidal amplitude each year (Fictional Data). In years from 1990 to 1992, tide was measured in centimeters, from 1993 to 1995 it was measured in milimeters.
<- data.frame(Year = c(1990:1995), height = c(130, 230, 210, 1450, 1870, 2200 )) tide.df
- Use
ifelse
statements to first print to screen whether each row is “pre-change” or “post-change” - Next use
ifelse
to create a new variable with the tidal amplitude in meters
<- data.frame(Year = c(1990:1995), height = c(13, 23, 21, 14, 18, 22))
tide.df ifelse(tide.df$Year <= 1992,"Pre-change", "Post-Change")
$height <- ifelse(tide.df$Year <= 1992,
tide.df$height/100,
tide.df$height/1000) tide.df