Challenge - 5 Problems
Matrix Apply Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of apply() on matrix rows
What is the output of this R code that uses
apply() on matrix rows?R Programming
mat <- matrix(1:9, nrow=3, byrow=TRUE) result <- apply(mat, 1, sum) print(result)
Attempts:
2 left
💡 Hint
Remember,
apply() with margin 1 applies the function to rows.✗ Incorrect
The matrix has rows: (1,2,3), (4,5,6), (7,8,9). Summing each row gives 6, 15, and 24.
❓ Predict Output
intermediate2:00remaining
Using apply() on matrix columns
What does this R code print when applying
mean on matrix columns?R Programming
mat <- matrix(c(2,4,6,8,10,12), nrow=2) result <- apply(mat, 2, mean) print(result)
Attempts:
2 left
💡 Hint
Margin 2 means apply function to columns.
✗ Incorrect
The matrix columns are (2,8), (4,10), (6,12). Their means are (5,7,9).
❓ Predict Output
advanced2:00remaining
Output of apply() with a custom function
What is the output of this R code applying a custom function to each row of a matrix?
R Programming
mat <- matrix(1:6, nrow=2) result <- apply(mat, 1, function(x) paste(x, collapse='-')) print(result)
Attempts:
2 left
💡 Hint
Margin 1 applies function to rows; matrix is filled column-wise by default.
✗ Incorrect
Matrix rows are (1,3,5) and (2,4,6). The function joins elements with '-'.
🔧 Debug
advanced2:00remaining
Identify the error in apply() usage
What error does this R code produce?
R Programming
mat <- matrix(1:9, nrow=3) result <- apply(mat, 3, sum) print(result)
Attempts:
2 left
💡 Hint
Check the dimensions of the matrix and the margin argument.
✗ Incorrect
The matrix has only 2 dimensions, margin 3 is invalid, causing the error "MARGIN must be between 1 and 2".
🧠 Conceptual
expert2:00remaining
Understanding apply() output type
Given this R code, what is the type and length of
result?R Programming
mat <- matrix(c(1,2,3,4), nrow=2) result <- apply(mat, 1, function(x) x * 2) str(result)
Attempts:
2 left
💡 Hint
When the function returns a vector, apply() simplifies to a matrix.
✗ Incorrect
The function doubles each row vector (length 2), so apply returns a 2x2 matrix.