Coalesce Data Frame Columns Row-Wise in R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write two R functions, `coalesce_columns(df, cols)` and `add_coalesced_column(df, cols, new_col)`. For each row, they pick the first non-missing value across a prioritized list of columns, like SQL `COALESCE`.
- `coalesce_columns` returns an atomic vector of length `nrow(df)` holding each row's first non-`NA` value among `cols`, checked left to right.
- A row where every column in `cols` is `NA` yields `NA`.
- The result type is the common type of the selected columns (for example `numeric` or `character`).
- `add_coalesced_column` returns `df` with the column `new_col` (a character scalar) added, or overwritten in place if it already exists, equal to `coalesce_columns(df, cols)`. The row count and the other columns stay unchanged.
- Both functions call `stop()` if `cols` has length 0 or if any name in `cols` is not a column of `df`.
Base R is enough; no packages are required.
Example:
```r
df <- data.frame(
a = c(NA, 2, NA),
b = c(10, NA, NA),
c = c(99, 99, 7)
)
coalesce_columns(df, c("a", "b", "c"))
# [1] 10 2 7
```
```hint Work by column
Scanning each row for its first value works, but count how many vectorized passes over whole columns you would need instead, and which positions each pass is allowed to write.
```
```hint Result type
Decide the output type before filling anything. Check what happens to a numeric vector when a character value is assigned into one of its positions, and what happens when a column never gets to contribute a value.
```
### What a Strong Answer Covers
- Input validation for an empty `cols` and for names that are not columns of `df`.
- Left-to-right priority, with each row taking its first non-missing value and all-`NA` rows staying `NA`.
- How the result type is decided, and why it should not depend on which columns happen to fill values.
- A vectorized implementation and its time and space cost.
- `add_coalesced_column` adding or replacing the column without changing the row count or the other columns.
### Follow-up Questions
- How would you handle mixed column types, for example coalescing an `integer` and a `character` column?
- How could you vectorize this without a per-row loop?
- How would you also treat empty strings or sentinel values such as `-999` as missing?
Overview: Write base R functions that pick each row's first non-missing value across prioritized data frame columns, like SQL COALESCE, and add it as a new column. It tests vectorized filling by column, input validation, and how R decides the common type of mixed columns.