Inner join two R data frames by ID and list the common IDs
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two R functions that inner-join two data frames on a shared key column, so only keys present in both frames survive.
- `inner_join_by_id(left, right, id_col)` returns a plain `data.frame` (not a tibble) of the rows whose `id_col` value appears in both inputs.
- Columns come in this order: `id_col`, then the remaining `left` columns, then the remaining `right` columns, each in their original order. Non-key column names are unique across the two frames.
- Rows are sorted ascending by `id_col`, and `row.names` are reset to 1 to n.
- `common_ids(left, right, id_col)` returns the unique `id_col` values present in both frames, sorted ascending, with the same type as the id column. It returns a length-0 vector when there is no overlap.
- Both functions call `stop()` if `id_col` is not a column of both frames.
Example:
```r
left <- data.frame(id = c(3, 1, 2), x = c("c", "a", "b"))
right <- data.frame(id = c(2, 1, 5), y = c(20, 10, 50))
inner_join_by_id(left, right, "id")
# id x y
# 1 1 a 10
# 2 2 b 20
common_ids(left, right, "id")
# [1] 1 2
```
```hint Output shape
After the join, list which parts of the required shape (column order, row order, row names, class, id type) the functions you call already guarantee, and set the rest yourself.
```
### What a Strong Answer Covers
- Validation of `id_col` against both frames before any other work.
- Which output properties come from the join and which are set explicitly: column order, row order, row names and class.
- A `common_ids` result that is unique, sorted, empty when nothing overlaps, and keeps the id column's type.
- The no-overlap case for both functions.
### Follow-up Questions
- How would you handle duplicate `id_col` values within a frame?
- Why does the contract require a plain `data.frame`, and what would change if you returned a tibble?
- Should rows with an `NA` key match each other, and what do `merge()` and a SQL inner join each do with them?
Overview: Write two base R functions: one inner-joins two data frames on a key column with a fixed column order, row order and row names, and the other returns the sorted ids shared by both frames in the id column's type. It tests merge semantics, output contracts and type-safe set operations in R.