Rename Data Frame Columns in R With dplyr rename and rename_with
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement three column-renaming helpers in R using dplyr's `rename` and `rename_with`. Each returns a `data.frame` of the same class and shape with only the column names changed: data, row order, column order and unlisted names stay intact.
- `rename_column(df, old_name, new_name)`: rename a single column (both arguments are length-1 strings). If `old_name` is missing, call `stop()`.
- `rename_columns(df, mapping)`: `mapping` is a named character vector whose names are the NEW names and whose values are the EXISTING names, for example `c(newA = "a", newB = "b")`. Rename every listed column.
- `clean_names(df)`: lower-case every column name using `rename_with`.
For example:
```r
df <- data.frame(a = 1:2, b = 3:4)
rename_column(df, "a", "x")
# x b -> columns renamed, values unchanged
rename_columns(df, c(newA = "a", newB = "b"))
# newA newB
clean_names(data.frame(Foo = 1, Bar = 2))
# foo bar
```
```hint Names held in variables
`old_name` and `mapping` arrive as character data stored in variables, not as bare column names. Look up how tidyselect wants an external character vector passed, and check which side of `new = old` each name goes on.
```
### What a Strong Answer Covers
- How column names stored in string variables are passed to `rename` safely.
- The direction of the mapping (new names as the vector's names, existing names as its values) and whether all renames are applied in one step.
- The error path when a name is missing, and what happens when a new name collides with an existing column.
- Why the class, data, row order, column order and untouched names come back unchanged.
### Follow-up Questions
- What happens when `mapping` swaps two names, such as `c(b = "a", a = "b")`? Does your code handle it?
- What should `clean_names` do when two names collide after lower-casing, such as `Foo` and `foo`?
- How would you write the same three helpers in base R without dplyr?
- How would you extend `clean_names` to also turn spaces and punctuation into underscores?
Overview: Implement three R helpers that rename one column, rename several columns from a named lookup vector, and lower-case every column name with dplyr. It tests passing column names stored in string variables to rename and rename_with, the direction of a new = old mapping, error handling for missing columns, and preserving the data frame's shape.