Implement a reproducible 70/30 train/validation split in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two functions in `/app/solution.R` that partition a data.frame into a training set and a validation set: `split_sizes(df, prop = 0.7)` and `train_val_split(df, prop = 0.7, seed = 42)`. The split must be exhaustive (every row lands in one of the sets), disjoint (no row lands in both) and identical across runs for the same `seed`.
Requirements:
- Both functions call `stop()` unless `prop` is a single number strictly between 0 and 1.
- `split_sizes` returns the named integer vector `c(train = k, validation = n - k)`, where `n = nrow(df)` and `k = floor(n * prop)`.
- `train_val_split` calls `set.seed(seed)`, then draws `train_idx <- sort(sample(seq_len(nrow(df)), size = floor(nrow(df) * prop)))`.
- The training set is `df[train_idx, , drop = FALSE]`. The validation set is every row not in `train_idx`, also taken with `drop = FALSE`. Both keep the original row order and row names.
- `train_val_split` returns `list(train = <data.frame>, validation = <data.frame>)`.
Example:
```r
df <- data.frame(x = 1:10)
split_sizes(df, prop = 0.7)
# train validation
# 7 3
res <- train_val_split(df, prop = 0.7, seed = 42)
nrow(res$train) # 7
nrow(res$validation) # 3
```
```hint Try the smallest inputs
Run your split on a one-row data frame with `prop = 0.7` and check that the row still ends up in one of the sets. Look at what `df[-integer(0), ]` returns.
```
### Constraints & Assumptions
- `df` is a data.frame with any number of rows (including 0 or 1) and any columns. Its row names may be custom.
- `prop` can arrive as any R value. Only a single, non-missing number strictly between 0 and 1 is valid.
- `seed` is passed straight to `set.seed()`.
### What a Strong Answer Covers
- One validation rule for `prop`, applied in both functions, that covers non-numeric input, length other than 1, `NA`, and the boundary values 0 and 1.
- Split sizes from `floor(n * prop)`, returned as a named integer vector.
- Seeding immediately before sampling, so the same seed always selects the same rows.
- Sets that stay disjoint and exhaustive, including when `floor(n * prop)` is 0.
- Row order, row names and the data.frame class preserved, with `drop = FALSE` for one-column inputs.
### Follow-up Questions
- How would you extend this to a stratified split by a class label?
- Why sort the sampled indices, and does sorting affect randomness?
- `set.seed()` changes the caller's global random number stream. How would you avoid that side effect?
- If the data holds several rows per customer, how would you split it so that no customer appears in both sets?
Overview: Implement a reproducible 70/30 train/validation split of an R data frame, with input checks on the split proportion. It tests seeded sampling, disjoint and exhaustive row partitions, and base R indexing pitfalls such as drop = FALSE and empty negative indices.