Add Comparison and Threshold Label Columns to an R Data Frame
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement two R functions that add a character column derived from comparing the numeric columns `a` and `b` of a data frame. Each function returns the same data frame with the new column added and the existing columns and row order unchanged.
- `add_comparison(df)` adds a column `comparison` that is `"greater"` when `a > b`, `"less"` when `a < b`, and `"equal"` when `a == b`.
- `add_diff_label(df, threshold)` adds a column `diff_label` that is `"close"` when `abs(a - b) <= threshold` and `"far"` otherwise.
- In both functions, a row with `NA` in `a` or `b` gets `NA_character_`.
For example:
```r
df <- data.frame(a = c(5, 2, 4, NA), b = c(3, 2, 9, 1))
add_comparison(df)$comparison
# "greater" "equal" "less" NA
add_diff_label(df, threshold = 1)$diff_label
# "far" "close" "far" NA
```
```hint Missing values
A comparison that involves `NA` returns `NA`, not `TRUE` or `FALSE`. Check what `ifelse` returns for such a row, and what type the new column ends up with.
```
### Constraints & Assumptions
- `df` has numeric columns `a` and `b` and may have other columns, which must be left as they are.
- `threshold` is a single number, and the boundary is inclusive: a difference equal to `threshold` is `"close"`.
### What a Strong Answer Covers
- Vectorized comparisons over whole columns, with no row-by-row loop.
- Handling of `NA` so that missing rows come out as `NA_character_` and the new column is a character vector.
- The inclusive `<=` at the threshold boundary.
- Returning the full data frame with the column appended and the rows in their original order.
### Follow-up Questions
- Why does `ifelse` propagate `NA` here, and in which cases can its result come back logical instead of character?
- How would you generalize `add_comparison` to arbitrary column names?
- How would you treat two values as equal when they differ only by floating-point error, such as `0.1 + 0.2` and `0.3`?
Overview: Write two R functions that add a character column to a data frame by comparing two numeric columns: a greater, less or equal label, and a close or far label based on a threshold. Tests vectorized ifelse, NA propagation, and keeping column types and row order intact.