0
0
R Programmingprogramming~20 mins

Apply functions on matrices in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Matrix Apply Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1] 12 15 18
B[1] 6 15 24
C[1] 3 6 9
D[1] 1 2 3
Attempts:
2 left
💡 Hint
Remember, apply() with margin 1 applies the function to rows.
Predict Output
intermediate
2: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)
A[1] 2 4 6
B[1] 4 6 8
C[1] 3 5 7
D[1] 5 7 9
Attempts:
2 left
💡 Hint
Margin 2 means apply function to columns.
Predict Output
advanced
2: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)
A[1] "1-2-3" "4-5-6"
B[1] "1-4" "2-5"
C[1] "1-3-5" "2-4-6"
D[1] "1-2" "3-4"
Attempts:
2 left
💡 Hint
Margin 1 applies function to rows; matrix is filled column-wise by default.
🔧 Debug
advanced
2: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)
AError in apply(mat, 3, sum) : MARGIN must be between 1 and 2
BError in apply(mat, 3, sum) : subscript out of bounds
CError in apply(mat, 3, sum) : incorrect number of dimensions
DNo error, prints sums of third dimension
Attempts:
2 left
💡 Hint
Check the dimensions of the matrix and the margin argument.
🧠 Conceptual
expert
2: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)
A"num [1:2, 1:2]" (a 2x2 numeric matrix)
B"num [1:2]" (a numeric vector of length 2)
C"list of 2" (a list with 2 elements)
D"num [1:4]" (a numeric vector of length 4)
Attempts:
2 left
💡 Hint
When the function returns a vector, apply() simplifies to a matrix.