Build a 3x3 integer matrix with row names in base R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement three base R functions that create integer vectors, combine them row-wise into a 3x3 matrix, and set the matrix's row names.
- `make_vectors()` takes no arguments and returns a named list with exactly `v1 = c(1L, 2L, 3L)`, `v2 = c(4L, 5L, 6L)` and `v3 = c(7L, 8L, 9L)`.
- `build_matrix(v1, v2, v3)` returns a 3x3 matrix with rows `v1`, `v2`, `v3` in that order, `storage.mode` equal to `"integer"`, and `dimnames` equal to `NULL`.
- `set_row_names(mat, row_names)` returns `mat` with its row names set and its column names unchanged (`NULL`).
- `set_row_names` calls `stop()` if `length(row_names) != nrow(mat)`.
Example:
```r
vs <- make_vectors()
m <- build_matrix(vs$v1, vs$v2, vs$v3)
m
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
# [3,] 7 8 9
m <- set_row_names(m, c("a", "b", "c"))
rownames(m) # "a" "b" "c"
```
```hint Check types and names after each step
Compare `typeof(c(1, 2, 3))` with `typeof(1:3)`, and print `dimnames()` of whatever `rbind` returns inside your function to see what it attaches.
```
### Constraints & Assumptions
- Base R only: no external packages.
- The three inputs to `build_matrix` are vectors of length 3, so the result is always 3x3.
### What a Strong Answer Covers
- How to create true integer vectors in R and how to confirm the type with `typeof()` or `storage.mode()`.
- Binding the vectors as rows in argument order and clearing the row names that `rbind` takes from the argument names.
- Forcing integer storage on the matrix even when a caller passes doubles.
- Checking the length of `row_names` before assigning, and leaving column names `NULL`.
### Follow-up Questions
- How do you force a vector to integer storage in R, and how do you confirm it worked?
- What happens to the matrix's storage mode if one of the three inputs is a double or a character vector?
- How would you generalize `build_matrix` to any number of equal-length vectors?
- What is the difference between `rownames(m) <- x` and `dimnames(m) <- list(x, NULL)`?
Overview: Write three base R functions that create integer vectors, bind them row-wise into a 3x3 matrix, and set validated row names. It tests integer storage modes, how rbind names its rows, and input checks with stop().