is_even(c(1, 3, 2, 4))
[1] FALSE FALSE TRUE TRUE
Aurélien Ginolhac
March 26, 2025
Write a for loop and understand it focuses on the iteration and not actions
If you use any AI tool, report its name and associated prompts next to your answers.
Any obvious AI answers un-flagged as such will not be considered.
Being lazy, instead of you doing the work, rely on the work of someone else | Hadley Wickham
For example, passing the vector c(1, 3, 2, 4)
to the function is_even()
should output:
if
, else if
, else
or a for
loop.res
vector with logicalsres
Start by writing a piece of code that does the job, following the steps of your pseudocode
is_even()
a %% b
in R and returns the remainder of the division of a/b
. If b = 2
and the result is different from zero, then a
is an odd number.a
equals b
using ==
and not =
. a = b
is an assignment leading a
to take the value of b
!What would happen if we provide some characters, or a matrix, as an input to is_even()
? Is your function able to deal with such an input?
No, but it should. Add a test before doing anything else to check if numbers are provided to the function.
x <- c(1, 3, 2, 4)
is_even <- function(x) {
# if the input is not numeric, we stop the code execution
# of note, the call. = FALSE is to avoid printing the code line, makes the error more explicit
if (!is.numeric(x)) stop("input not numeric!", call. = FALSE)
if (length(x) == 0) stop("input cannot be empty!", call. = FALSE)
res <- vector(mode = "logical", length = length(x))
for (i in x) { # iterate all elements, R will do from 1 to length(x)
res[i] <- x[i] %% 2 == 0 # %% is the modulo operator
}
res
}
is_even(x)
[1] FALSE FALSE TRUE TRUE
Error: input not numeric!
Error: input cannot be empty!
Now that the for loop was a pain to set-up, we can use what is good at: vectorization
for
loop code with one line of vectorizationis_even <- function(x) {
if (!is.numeric(x)) stop("input not numeric!", call. = FALSE)
# the vector is integer divided by 2, the iteration is transparent
# then logical test: is different from 0
# finally sum up the logical vector, TRUE is 1, FALSE is 0
x %% 2 == 0
}
is_even(x)
[1] FALSE FALSE TRUE TRUE
Such as:
Such as: