Run k-means in R and build a deterministic per-cluster summary
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement two R functions that cluster a numeric dataset with `stats::kmeans()` and produce a deterministic per-cluster summary.
- `run_kmeans(data, features, k, seed = 42)`: coerce `data[, features]` to a numeric matrix and call `set.seed(seed)` immediately before `stats::kmeans(centers = k)`. Return a list with `cluster` (integer, length `nrow(data)`, values `1..k`), `centers` (a `k` x `length(features)` matrix), `size` (integer, length `k`) and `tot_withinss` (a numeric scalar).
- `cluster_summary(data, features, k, seed = 42)`: call `run_kmeans()` and return a `data.frame` with columns `cluster` (integer), `size` (integer), then one per-cluster mean column per feature. Order the rows ascending by the mean of the first feature, renumber `cluster` as `1..k` in that order, and reset the row names.
Both functions must call `stop()` if any name in `features` is not a column of `data`, or if `k < 1` or `k > nrow(data)`.
Example:
```r
res <- run_kmeans(iris, c("Sepal.Length", "Petal.Length"), k = 3)
res$cluster # integer vector, length 150, values 1..3
res$centers # 3 x 2 numeric matrix
res$size # integer vector, length 3
res$tot_withinss # numeric scalar
cluster_summary(iris, c("Sepal.Length", "Petal.Length"), k = 3)
# cluster size Sepal.Length Petal.Length
# 1 1 ... ... ... # rows ordered by mean Sepal.Length
```
On two well-separated groups the summary is the same for any seed:
```r
toy <- data.frame(a = c(1, 2, 3, 101, 102, 103), b = c(5, 6, 7, 1, 2, 3))
cluster_summary(toy, c("a", "b"), k = 2)
# cluster size a b
# 1 1 3 2 6
# 2 2 3 102 2
```
```hint Labels carry no meaning
The numbers `kmeans()` gives its clusters are arbitrary and can change with the seed. The summary has to be built from quantities that do not depend on those numbers.
```
```hint Matching rows to clusters
Functions such as `rowsum()`, `aggregate()` and `tapply()` compute per-group values in one call. Check the order their output rows come back in before lining them up with `size`.
```
### Constraints & Assumptions
- Only the packages that ship with R are available.
- `kmeans()` cannot handle missing or infinite values, so the feature columns must hold finite numbers.
- Visualization is not graded.
### What a Strong Answer Covers
- Validation of the feature names and the range of `k` before any fitting
- `set.seed(seed)` called immediately before `stats::kmeans()`, and the four list components returned with the required types
- Per-cluster sizes and feature means computed from the data and matched to the right cluster
- Rows reordered by the first feature's mean, clusters renumbered `1..k`, and row names reset
- Why raw k-means labels are arbitrary and how the reordering makes the output deterministic
### Follow-up Questions
- How would you choose a good value of `k`?
- Why standardize features before clustering?
- Why does `set.seed()` matter here?
- What would passing `nstart = 10` to `kmeans()` change, and how would it affect this contract?
Overview: Write two R functions that run stats::kmeans() with input validation and a fixed seed, then build a per-cluster summary of sizes and feature means ordered by the first feature. It tests reproducible clustering, cluster relabeling and grouped means in base R.