Recall & Review
beginner
What function in R is commonly used to apply a function to the rows or columns of a matrix?
The
apply() function is used to apply a function to the rows or columns of a matrix in R.Click to reveal answer
beginner
How do you specify whether to apply a function to rows or columns in the
apply() function?You use the
MARGIN argument: 1 for rows and 2 for columns.Click to reveal answer
beginner
Example: What does
apply(mat, 1, sum) do if mat is a matrix?It calculates the sum of each row in the matrix
mat, returning a vector of row sums.Click to reveal answer
beginner
Can you use
apply() to find the mean of each column in a matrix? How?Yes. Use
apply(mat, 2, mean) to calculate the mean of each column.Click to reveal answer
intermediate
What is the difference between
apply() and lapply() in R?apply() works on matrices or arrays applying a function over rows or columns, while lapply() works on lists applying a function to each element.Click to reveal answer
In R, what does
apply(mat, 2, sum) do?✗ Incorrect
MARGIN = 2 means apply the function to columns, so it sums each column.Which argument in
apply() specifies whether to apply a function to rows or columns?✗ Incorrect
MARGIN is used to specify rows (1) or columns (2).What will
apply(mat, 1, mean) return?✗ Incorrect
MARGIN = 1 applies the function to rows, so it returns the mean of each row.If you want to apply a function to each element of a list, which function is more appropriate than
apply()?✗ Incorrect
lapply() applies a function to each element of a list.What type of object does
apply() expect as input?✗ Incorrect
apply() is designed for matrices or arrays.Explain how to use the
apply() function to calculate the sum of each row in a matrix.Remember MARGIN = 1 means rows.
You got /5 concepts.
Describe the difference between
apply() and lapply() in R and when to use each.Think about the data structure you have.
You got /5 concepts.