Find the Position and Row of the Maximum in R With which()
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement three R functions that locate the maximum of a numeric vector or data frame column using `which()`. `NA` values are ignored when finding the maximum.
- `first_max_index(x)` returns an integer scalar, the 1-based position of the first maximum of `x`.
- `all_max_indices(x)` returns an integer vector of all positions equal to the maximum, in increasing order.
- `row_of_max(df, col)` returns an integer scalar, the row number of the first maximum in `df[[col]]`.
Example:
```r
first_max_index(c(3, 7, 7, 2)) # 2
all_max_indices(c(3, 7, 7, 2)) # c(2, 3)
df <- data.frame(a = c(1, 5, 5, 4))
row_of_max(df, "a") # 2
```
```hint Watch the NA positions
Work out what `x == m` gives at a position where `x` is `NA`, and what `which()` does with that value.
```
### What a Strong Answer Covers
- Computing the maximum once with `NA` removed, then locating it with `which()`
- Why `NA` entries drop out of the result without explicit filtering
- First occurrence versus all occurrences when the maximum is tied, returned as ascending integers
- Defined behavior for empty or all-`NA` input and for a column name that is not in `df`
- What "row number" means in `row_of_max` when the data frame has non-default row names
### Follow-up Questions
- Why does `which.max()` alone not satisfy `all_max_indices()`?
- Is comparing doubles with `==` safe here? When would it give a surprising answer?
- How would you change `row_of_max` to return the row name or the whole row instead of the position?
Overview: Write three R functions that use which() to find the first position of a maximum, every tied position, and the data frame row holding the maximum, while ignoring NA values. It tests how comparisons with NA behave, tie handling, and checks for empty or all-missing input.