Correlation Matrix, Long Form and Most Correlated Pair in Base R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement three base R functions that compute a Pearson correlation matrix over a data frame's numeric columns, reshape it to long form, and find the most correlated pair. No plotting is required.
- `correlation_matrix(df)` uses only the numeric columns and returns the square `cor()` matrix, with row and column names equal to the numeric column names. It calls `stop()` if there are fewer than 2 numeric columns.
- `correlation_long(df)` returns a data.frame with the columns `var1` (character), `var2` (character) and `correlation` (numeric), in that order. It has one row per ordered pair of numeric columns, self-pairs included, so ${n^2}$ rows for $n$ numeric columns. Rows are sorted ascending by `var1` and then `var2`, and the row names are reset to 1 through ${n^2}$.
- `most_correlated_pair(df)` looks at the distinct off-diagonal pairs (the upper triangle) and picks the one with the largest absolute correlation. It returns `list(var1 = <character>, var2 = <character>, correlation = <numeric, signed>)`. If several pairs share the largest absolute value, it returns the first one met when scanning the upper triangle row by row in the matrix's column order: (1, 2), (1, 3), and so on, then (2, 3).
For example:
```r
df <- data.frame(a = c(1, 2, 3, 4), b = c(2, 4, 6, 8), c = c(4, 3, 2, 1),
grp = c("x", "y", "x", "y"))
correlation_matrix(df) # 3x3 matrix over a, b, c (grp dropped)
correlation_long(df) # 9 rows: (a,a), (a,b), (a,c), (b,a), ...
most_correlated_pair(df)
# list(var1 = "a", var2 = "b", correlation = 1)
```
```hint Compute once
Build the correlation matrix in one function and derive the other two outputs from that matrix.
```
```hint Equal values
In the example every off-diagonal pair has the same absolute correlation. Check which comparison operator keeps the first pair when a later one ties it.
```
### Constraints & Assumptions
- Base R only.
- A column is numeric when `is.numeric()` is `TRUE` for it, which covers double and integer columns. Character, factor and logical columns are dropped.
- Correlations are Pearson correlations with the `cor()` defaults.
### What a Strong Answer Covers
- Selecting the numeric columns in a way that keeps a data frame, and failing with `stop()` when fewer than two remain.
- Reshaping the matrix into ${n^2}$ rows with character `var1` and `var2`, the required sort order and reset row names.
- Scanning only the cells with $i < j$, ranking by absolute value and returning the signed correlation.
- A tie-break that produces the same pair on every run, and what happens when `cor()` returns `NA`.
### Follow-up Questions
- How would you handle columns with zero variance, which make `cor()` return `NA`?
- The tie-break depends on column order. What happens if the input columns are reordered, and how would you make the result independent of their order?
- How would you return the top $k$ pairs instead of one?
- When would you use Spearman correlation instead of Pearson?
Overview: Write three base R functions that compute a Pearson correlation matrix over the numeric columns of a data frame, reshape it into a sorted long table, and return the most strongly correlated pair with its sign. Tests column selection, matrix reshaping and a deterministic tie-break.