Recall & Review
beginner
What is the main difference between the apply family of functions and loops in R?
The apply family functions are vectorized and often faster, allowing you to apply a function over elements of a list, vector, or matrix without explicitly writing a loop. Loops require you to write the iteration manually and can be slower for large data.
Click to reveal answer
beginner
Name three functions from the apply family in R and their typical use cases.
- apply(): Apply a function over the rows or columns of a matrix.
- lapply(): Apply a function over each element of a list and return a list.
- sapply(): Similar to lapply but tries to simplify the result to a vector or matrix.
Click to reveal answer
beginner
Why might you prefer using apply functions over loops in R?
Apply functions often lead to cleaner, shorter code and can be more efficient because they are optimized internally. They also reduce the chance of errors from manual indexing in loops.
Click to reveal answer
beginner
What does the following R code do? <br>
result <- sapply(1:5, function(x) x^2)
It applies the anonymous function that squares a number to each element in the vector 1 to 5, returning a vector of squared numbers: 1, 4, 9, 16, 25.
Click to reveal answer
intermediate
How can you rewrite a for loop that sums each column of a matrix using apply?
Instead of looping through columns, use
apply(matrix, 2, sum) where 2 means columns. This applies the sum function to each column and returns a vector of sums.Click to reveal answer
Which apply function returns a list as output?
✗ Incorrect
lapply() always returns a list, applying a function to each element of a list or vector.
What does the '2' mean in the function call apply(X, 2, FUN)?
✗ Incorrect
In apply, 1 means rows and 2 means columns.
Which is generally faster for large data in R?
✗ Incorrect
Apply family functions are optimized and usually faster than explicit loops.
What type of object does sapply() try to return?
✗ Incorrect
sapply() tries to simplify the output to a vector or matrix if possible.
Which apply function is best to use for grouped operations on a factor?
✗ Incorrect
tapply() applies a function over subsets of a vector defined by a factor.
Explain the advantages of using the apply family of functions over traditional loops in R.
Think about how apply functions handle iteration internally.
You got /4 concepts.
Describe how you would use apply() to calculate the mean of each row in a matrix.
Remember the margin argument controls rows or columns.
You got /4 concepts.