Row-wise Maximum of a Matrix or Data Frame in R With NA Handling
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `rowwise_max(x, na.rm = TRUE)` in R. Given a numeric matrix or an all-numeric data frame, return a numeric vector of length `nrow(x)` with each row's maximum.
- With `na.rm = TRUE`, ignore `NA`s. An all-`NA` row yields `NA_real_`, never `-Inf`.
- With `na.rm = FALSE`, any `NA` in a row makes that row's result `NA`.
- Carry the row names of `x` onto the result; otherwise the result has no names.
- Call `stop()` if `x` is neither a matrix nor a data frame.
- Call `stop()` if the data is non-numeric (for example a character matrix, or a data frame with a non-numeric column).
Example:
```r
m <- matrix(c(1, NA, 3,
NA, NA, NA,
4, 2, 6), nrow = 3, byrow = TRUE)
rowwise_max(m, na.rm = TRUE) # c(3, NA, 6)
rowwise_max(m, na.rm = FALSE) # c(NA, NA, 6)
```
```hint The empty row
Check what `max()` returns, and what it warns about, when every value in a row has been removed.
```
```hint Check types before converting
Consider what `as.matrix()` does to a data frame that mixes a logical column with numeric ones, and whether a type check on the resulting matrix would still catch it.
```
### Clarifying Questions to Ask
- A data frame with default row names (`"1"`, `"2"`, ...) technically has row names. Should those be carried onto the result, or treated as no row names?
- Should integer input return a double vector, so the result type is the same for every input?
- What should a matrix with zero columns return when `na.rm = FALSE`, where each row has no values at all?
### What a Strong Answer Covers
- Validating the input class and the type of every data frame column before any coercion
- Reducing both input types to one numeric matrix so a single row-processing path handles them
- Returning `NA_real_` for all-`NA` rows when `na.rm = TRUE`, and `NA` for any row with a missing value when `na.rm = FALSE`
- Carrying row names correctly for both matrices and data frames
- Time and memory cost, and a faster approach for very tall inputs
### Follow-up Questions
- How would you make this efficient for a very tall matrix?
- Why return `NA_real_` for an all-`NA` row instead of letting `-Inf` through?
- How does your function treat `NaN`, and should it be distinguished from `NA`?
Overview: Implement an R function that returns the maximum of each row of a numeric matrix or data frame, with na.rm control, all-NA rows mapped to NA, row names kept, and input validation. It tests NA semantics in base R, type checks before coercion, and faster options for very tall inputs.