Apply functions on matrices in R Programming - Time & Space Complexity
When we apply functions on matrices in R, we want to know how the time to run the code changes as the matrix gets bigger.
We ask: How does the work grow when the matrix size grows?
Analyze the time complexity of the following code snippet.
m <- matrix(1:10000, nrow=100, ncol=100)
result <- apply(m, 1, sum) # sum each row
This code sums each row of a matrix with 100 rows and 100 columns.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Summing elements in each row of the matrix.
- How many times: The sum operation repeats once for each row (100 times here).
As the matrix grows, the time to sum each row grows with the number of rows and columns.
| Input Size (n x n) | Approx. Operations |
|---|---|
| 10 x 10 | 100 sums (10 rows x 10 columns) |
| 100 x 100 | 10,000 sums (100 rows x 100 columns) |
| 1000 x 1000 | 1,000,000 sums (1000 rows x 1000 columns) |
Pattern observation: The total work grows roughly by the square of the matrix size because each element is visited once.
Time Complexity: O(n * m)
This means the time grows proportionally to the number of rows times the number of columns in the matrix.
[X] Wrong: "Applying a function on rows only depends on the number of rows."
[OK] Correct: Each row operation processes all columns, so columns also affect the time.
Understanding how function application scales on matrices helps you reason about data processing tasks and optimize code in real projects.
"What if we applied the function on columns instead of rows? How would the time complexity change?"
Practice
apply() function do when used on a matrix?Solution
Step 1: Understand the purpose of apply()
Theapply()function is designed to run a function on margins of an array or matrix.Step 2: Identify what margins mean in a matrix
Margin 1 means rows, margin 2 means columns. Soapply()runs the function on each row or column.Final Answer:
It applies a function to each row or column of the matrix. -> Option DQuick Check:
apply() = function on rows/columns [OK]
- Thinking apply() changes matrix shape automatically
- Confusing apply() with sorting or vector conversion
- Using apply() without specifying margin
m using apply() in R?Solution
Step 1: Identify margin for columns
Inapply(), margin 2 means columns.Step 2: Check function placement
The function to apply (sum) is the third argument, so syntax isapply(m, 2, sum).Final Answer:
apply(m, 2, sum) -> Option AQuick Check:
sum columns = apply(m, 2, sum) [OK]
- Using margin=1 for columns instead of 2
- Swapping function and margin arguments
- Missing the function argument
m <- matrix(1:6, nrow=2) apply(m, 1, max)
Solution
Step 1: Understand the matrix structure
The matrixmis created with values 1 to 6, 2 rows: Row 1: 1, 3, 5 Row 2: 2, 4, 6Step 2: Apply max function on rows (margin=1)
Max of row 1 is 5, max of row 2 is 6.Final Answer:
[1] 5 6 -> Option CQuick Check:
max per row = 5, 6 [OK]
- Confusing rows and columns in margin
- Misreading matrix values
- Assuming apply returns matrix instead of vector
m <- matrix(1:9, nrow=3) apply(m, 3, mean)
Solution
Step 1: Check matrix dimensions
The matrixmhas 2 dimensions (rows and columns).Step 2: Validate margin argument
Margin 3 refers to a third dimension, which does not exist in a 2D matrix.Final Answer:
Margin 3 is invalid for a 2D matrix. -> Option BQuick Check:
Margin must be 1 or 2 for matrices [OK]
- Using margin > 2 for 2D matrices
- Assuming apply works on non-existent dimensions
- Confusing apply() with array functions
m of numeric values. You want to create a new vector that contains the mean of each row but only for rows where the sum is greater than 10. Which R code correctly does this using apply()?Solution
Step 1: Understand the requirement
We want mean of each row only if that row's sum is > 10, else exclude it.Step 2: Analyze each option
A returns NA for rows not >10 but does not remove them. C incorrectly filters inside mean. D uses margin=2 (columns) instead of rows.Step 3: Correct approach
apply(m, 1, function(x) if(sum(x) > 10) mean(x) else NA)[!is.na(.)] returns NA for rows with sum ≤ 10, then removes NAs with[!is.na(.)], giving only desired means.Final Answer:
apply(m, 1, function(x) if(sum(x) > 10) mean(x) else NA)[!is.na(.)] -> Option AQuick Check:
Filter rows by sum > 10, then mean [OK]
- Using margin=2 instead of 1 for rows
- Not handling rows with sum ≤ 10 properly
- Trying to filter inside mean() incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
