Recall & Review
beginner
What does the
ifelse() function do in R?It checks a condition for each element of a vector and returns a value if TRUE and another if FALSE, all in a vectorized way.
Click to reveal answer
beginner
How does
ifelse() handle vectors?It tests each element of the condition vector separately and returns a vector of the same length with values chosen from the 'yes' or 'no' arguments.
Click to reveal answer
beginner
What is the syntax of
ifelse()?ifelse(test, yes, no)where
test is a logical vector, yes is returned if TRUE, and no if FALSE.Click to reveal answer
intermediate
Why is
ifelse() preferred over a loop for element-wise conditions?Because it is vectorized, making it faster and simpler to write than looping through each element manually.
Click to reveal answer
intermediate
What happens if the lengths of
yes or no arguments differ from the condition vector in ifelse()?R recycles the shorter vector to match the length of the condition vector, which can lead to unexpected results if not careful.
Click to reveal answer
What does
ifelse(c(TRUE, FALSE), 1, 0) return?✗ Incorrect
The function returns 1 where condition is TRUE and 0 where FALSE, so the result is [1, 0].
Which of these is TRUE about
ifelse() in R?✗ Incorrect
ifelse() is vectorized and works element-wise on vectors.What will
ifelse(c(TRUE, FALSE, TRUE), 'yes', 'no') output?✗ Incorrect
It returns 'yes' for TRUE elements and 'no' for FALSE elements.
If the 'yes' argument is shorter than the condition vector, what does
ifelse() do?✗ Incorrect
R recycles shorter vectors to match the length of the condition vector.
Which is a good use case for
ifelse()?✗ Incorrect
ifelse() is designed for element-wise conditional assignment.Explain how the
ifelse() function works in R and why it is useful.Think about how it handles each element of a vector and why that helps.
You got /4 concepts.
Describe what happens when the lengths of the 'yes' or 'no' arguments differ from the condition vector in
ifelse().Consider how R handles vectors of different lengths in operations.
You got /3 concepts.