0
0
R Programmingprogramming~5 mins

Ifelse vectorized function in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A[0, 1]
B[TRUE, FALSE]
C[1, 0]
D[1]
Which of these is TRUE about ifelse() in R?
AIt works element-wise on vectors.
BIt only works on single TRUE or FALSE values.
CIt cannot return vectors.
DIt is slower than loops.
What will ifelse(c(TRUE, FALSE, TRUE), 'yes', 'no') output?
Ac('yes', 'no', 'yes')
Bc('no', 'yes', 'no')
Cc(TRUE, FALSE, TRUE)
Dc('yes')
If the 'yes' argument is shorter than the condition vector, what does ifelse() do?
AReturns only the first element.
BRecycles the 'yes' vector to match the length.
CIgnores extra elements in the condition.
DThrows an error.
Which is a good use case for ifelse()?
ASorting a vector.
BReading files from disk.
CCreating plots.
DAssigning values based on a condition to each element of a vector.
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.