Professional Documents
Culture Documents
Exercises Controlloop Solutions
Exercises Controlloop Solutions
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
1
x <- NULL
for (i in 1:99999999) {
x <- c(x, sample(x = 1:10, size = 1))
if (sum(x) >= 100) break
}
x
# or
for (i in animals) print(i)