Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Control Structures: Exercises

Prof. Dr. Salmai Qari

if/else vs. ifelse vs. logical subsetting


1. The following dataframe contains for 9 students the grades and the information whether the respective
student cheated or not.
df <- data.frame(id = 1:9,
grade = c(2, 5, 3, 1, 6, 1, 4, 3, 1),
cheated = c(FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE))

Those who cheated get a grade 5. Set the value of grade to 5 for all students who cheated. . .
a) . . . using a for loop and if (loop over the row numbers)
b) . . . using the vectorized version ifelse
c) . . . using subsetting
Hints:
• Use seq_along to loop over the row number
• Subsetting means an expression similar to x[x < 3]
• You can select a variable of a dataframe by using $, e.g., df$grade
• Check your result by displaying df
# a)
for (rownumber in seq_along(df$grade)) {
if (df$cheated[rownumber]) df$grade[rownumber] <- 5
}

# or
for (rownumber in seq_along(df$grade)) {
if (df$cheated[rownumber]) {
df$grade[rownumber] <- 5
}
}
# Remark: You don't need to write "df$cheated == TRUE" because df$cheated already
# contains logical values!

# b)
df$grade <- ifelse(df$cheated, 5, df$grade)

# c)
df$grade[df$cheated] <- 5

Loops: for vs. while


2. In general, every for loop can be written as a while loop and vice versa. But in many cases, one of
them is the better choice. Unfortunately, the author of the following loops did not make a good choice.
a) Rewrite the following for loop as a while loop.

1
x <- NULL
for (i in 1:99999999) {
x <- c(x, sample(x = 1:10, size = 1))
if (sum(x) >= 100) break
}
x

Why is this for loop so dangerous?


x <- NULL
while (sum(x) < 100) {
x <- c(x, sample(x = 1:10, size = 1))
}
x
# Version with "for" is not recommended
#because it could theoretically lead to an undesired result if the break
# condition is not met before it reaches 99999999.
# in this particular case it can't happen, because in each step we add at least 1.

b) Rewrite the following while loop as a for loop:


animals <- c("dog", "cat", "mouse", "snail")
i <- 1
while (i <= length(animals)) {
print(animals[i])
i <- i + 1
}
animals <- c("dog", "cat", "mouse", "snail")
for (i in animals) {
print(i)
}

# or
for (i in animals) print(i)

# or, a bit longer:


for (i in seq_along(animals)) {
print(animals[i])
}

You might also like