Remove Columns From an R Data Frame: Drop, Keep and Constant Columns
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement three base-R column helpers with no side effects. Each takes a `data.frame` and returns a new `data.frame`.
- `drop_columns(df, cols)`: remove the columns named in `cols`, preserving the order of the remaining columns. Unknown names are ignored.
- `keep_columns(df, cols)`: return only the columns named in `cols`, in the given order. Unknown names are ignored.
- `drop_constant_columns(df)`: remove columns where `length(unique(x)) == 1`, preserving the original order.
- Always return a `data.frame`, even with 0 or 1 columns.
For example:
```r
df <- data.frame(a = 1:3, b = c(5, 5, 5), c = c("x", "y", "z"))
drop_columns(df, c("b")) # columns a, c
keep_columns(df, c("c", "a")) # columns c, a (in that order)
drop_constant_columns(df) # drops b (constant); keeps a, c
```
```hint Watch the one-column case
Run `df[, "a"]` on a small frame and check the `class()` of the result. Then try indexing with a column name the frame does not have.
```
### What a Strong Answer Covers
- How each helper builds the set of columns to keep, and whose order it follows (the frame's for drops, the caller's for keeps).
- How unknown names are ignored without raising an error.
- How the result stays a `data.frame` when zero or one column remains.
- How constant columns are detected, including what happens with `NA` values and very small frames.
- Why the caller's data frame is left unchanged.
### Follow-up Questions
- How should `drop_constant_columns` treat columns that contain `NA`, and how would you change it to ignore missing values?
- What happens to your helpers when the data frame has duplicate column names?
- How would you write the same three helpers with dplyr?
Overview: Write three base R helpers that drop named columns, keep columns in a caller-given order, and remove constant columns from a data frame without side effects. It tests column subsetting, control of column order, ignoring unknown names, and returning a data.frame even when only one column is left.