Useful vector functions (length, sum, mean) in R Programming - Time & Space Complexity
We want to know how the time needed to run vector functions changes as the vector gets bigger.
How does the work grow when using length, sum, or mean on a vector?
Analyze the time complexity of the following code snippet.
# Create a numeric vector
vec <- c(1, 2, 3, 4, 5)
# Get the length of the vector
len <- length(vec)
# Calculate the sum of the vector elements
s <- sum(vec)
# Calculate the mean of the vector elements
m <- mean(vec)
This code finds how many items are in the vector, adds them all up, and then finds their average.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: sum() and mean() go through each item in the vector once.
- How many times: They look at every element one time each.
- length() operation: Just reads the vector size without looping.
As the vector gets bigger, sum() and mean() take longer because they check each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions for sum and mean |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to sum or average grows in a straight line with the number of elements.
[X] Wrong: "length() takes as long as sum() or mean() because it counts items one by one."
[OK] Correct: length() just reads the stored size quickly without checking each element, so it runs very fast no matter the vector size.
Understanding how simple vector functions scale helps you reason about performance in data tasks and shows you can think about efficiency clearly.
"What if we used a function that squared each element before summing? How would the time complexity change?"
Practice
length() function do when applied to a vector in R?Solution
Step 1: Understand the purpose of length()
Thelength()function counts how many items are inside a vector.Step 2: Compare with other functions
Unlikesum()ormean(), it does not add or average values, just counts them.Final Answer:
It returns the number of elements in the vector. -> Option DQuick Check:
length() = count elements [OK]
- Confusing length() with sum() or mean()
- Thinking length() returns the last element
- Assuming length() sorts the vector
v in R?Solution
Step 1: Recall function call syntax in R
Functions are called with parentheses and the vector inside, likemean(v).Step 2: Check each option
mean(v) uses correct syntax. Options B, C, and D are invalid or incorrect syntax.Final Answer:
mean(v) -> Option AQuick Check:
Function call uses parentheses: mean(v) [OK]
- Using square brackets instead of parentheses
- Assigning mean instead of calling it
- Omitting parentheses after function name
v <- c(2, 4, 6, 8) sum(v) + length(v)
Solution
Step 1: Calculate sum(v)
The vectorvisc(2,4,6,8). Sum is 2+4+6+8 = 20.Step 2: Calculate length(v) and add
Length is number of elements = 4. Adding sum + length = 20 + 4 = 24.Final Answer:
24 -> Option CQuick Check:
sum=20 + length=4 = 24 [OK]
- Adding elements incorrectly
- Confusing length with sum
- Forgetting to add length to sum
x. What is wrong?x <- c(5, 10, 15) mean = mean(x) print(mean)
Solution
Step 1: Analyze variable assignment
Assigningmean = mean(x)overwrites the built-inmean()function with a number.Step 2: Understand consequences
After this, callingmean()again will cause errors becausemeanis no longer a function.Final Answer:
The variable name 'mean' overwrites the function mean(), causing errors later. -> Option BQuick Check:
Don't name variables same as functions [OK]
- Thinking print() cannot print variables
- Believing mean() needs two arguments
- Ignoring variable shadowing of functions
nums with some missing values (NA). Which R code correctly calculates the mean ignoring the missing values?Solution
Step 1: Understand NA handling in mean()
To ignore missing values, use the argumentna.rm = TRUEinsidemean().Step 2: Check each option
mean(nums, na.rm = TRUE) uses correct argumentna.rm. Options B and D use incorrect argument names. sum(nums) / length(nums) does not handle NA and will return NA.Final Answer:
mean(nums, na.rm = TRUE) -> Option AQuick Check:
Use na.rm=TRUE to ignore NA in mean() [OK]
- Using wrong argument names like remove.na or na.ignore
- Calculating mean manually without handling NA
- Ignoring that NA causes mean() to return NA
Ready to prove it?
Pass the test and this pattern moves unknown
