Add Derived Columns to an R Data Frame: Row Index, Full Name, BMI and Price With Tax
Quick Overview
Write four small R functions that each append one derived column to a data frame: a row index, a joined full name, BMI and price with tax. It tests vectorized column assignment, keeping column order, the zero-row case and how R copies a data frame on modification.
Add Derived Columns to an R Data Frame: Row Index, Full Name, BMI and Price With Tax
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
In R, implement four functions that each take a `data.frame`, append exactly one new column as the last column (original columns preserved in order), and return it.
The functions and the column each one adds:
- `add_row_index(df)`: integer column `id` = `1..nrow(df)` (an empty integer vector for a 0-row frame).
- `add_full_name(df)`: `full_name` = the character columns `first` and `last` joined by a single space.
- `add_bmi(df)`: numeric `bmi` = `weight_kg / (height_m^2)`.
- `add_price_with_tax(df, rate)`: numeric `price_with_tax` = `price * (1 + rate)` (scalar `rate`).
Example:
```r
df <- data.frame(first = "Ada", last = "Lovelace", stringsAsFactors = FALSE)
add_full_name(df)
#> first last full_name
#> 1 Ada Lovelace Ada Lovelace
add_row_index(data.frame(x = c(10, 20, 30)))
#> x id
#> 1 10 1
#> 2 20 2
#> 3 30 3
```
```hint Zero rows
Check what `1:nrow(df)` and `seq_len(nrow(df))` each return when the frame has no rows.
```
### What a Strong Answer Covers
- Adding each column by assignment so it lands last and the existing columns keep their order.
- A row index that is also correct for a 0-row frame.
- Vectorized string joining and arithmetic with the right separator and formula.
- Why the caller's data frame is not changed, and what each function returns.
### Follow-up Questions
- How would you write a generic `add_column(df, name, values)` helper the four functions delegate to?
- What does `add_full_name` produce when `first` or `last` is `NA`, and how would you keep the result missing instead?
- How would you write the same four functions with dplyr?
Overview: Write four small R functions that each append one derived column to a data frame: a row index, a joined full name, BMI and price with tax. It tests vectorized column assignment, keeping column order, the zero-row case and how R copies a data frame on modification.
In R, implement four functions that each take a data.frame, append exactly one new column as the last column (original columns preserved in order), and return it.
The functions and the column each one adds:
add_row_index(df)
: integer column
id
=
1..nrow(df)
(an empty integer vector for a 0-row frame).
add_full_name(df)
:
full_name
= the character columns
first
and
last
joined by a single space.