Concept Flow - Useful vector functions (length, sum, mean)
Start with a vector
Calculate length
Calculate sum
Calculate mean
Output results
Start with a vector, then find its length, sum, and mean step-by-step, outputting each result.
vec <- c(2, 4, 6, 8) len <- length(vec) s <- sum(vec) m <- mean(vec) print(len) print(s) print(m)
| Step | Action | Expression | Result |
|---|---|---|---|
| 1 | Create vector | vec <- c(2, 4, 6, 8) | vec = c(2, 4, 6, 8) |
| 2 | Calculate length | length(vec) | 4 |
| 3 | Calculate sum | sum(vec) | 20 |
| 4 | Calculate mean | mean(vec) | 5 |
| 5 | Print length | print(len) | 4 |
| 6 | Print sum | print(s) | 20 |
| 7 | Print mean | print(m) | 5 |
| 8 | End | No more code | Execution stops |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| vec | undefined | c(2, 4, 6, 8) | c(2, 4, 6, 8) | c(2, 4, 6, 8) | c(2, 4, 6, 8) | c(2, 4, 6, 8) |
| len | undefined | undefined | 4 | 4 | 4 | 4 |
| s | undefined | undefined | undefined | 20 | 20 | 20 |
| m | undefined | undefined | undefined | undefined | 5 | 5 |
Useful vector functions in R: - length(vec): counts elements in vec - sum(vec): adds all elements - mean(vec): average of elements Store results in variables to reuse Print results to see output
length() function do when applied to a vector in R?length() function counts how many items are inside a vector.sum() or mean(), it does not add or average values, just counts them.v in R?mean(v).v <- c(2, 4, 6, 8) sum(v) + length(v)
v is c(2,4,6,8). Sum is 2+4+6+8 = 20.x. What is wrong?x <- c(5, 10, 15) mean = mean(x) print(mean)
mean = mean(x) overwrites the built-in mean() function with a number.mean() again will cause errors because mean is no longer a function.nums with some missing values (NA). Which R code correctly calculates the mean ignoring the missing values?na.rm = TRUE inside mean().na.rm. Options B and D use incorrect argument names. sum(nums) / length(nums) does not handle NA and will return NA.Pass the test and this pattern moves unknown