Reshape data between wide and long formats in R with tidyr pivots

Quick Overview

Write three R helpers with tidyr and dplyr: one pivots a wide data frame to long, one pivots it back to wide, and one summarizes each metric's mean and non-missing count. Tests pivot_longer and pivot_wider, deterministic column and row order, and returning clean base data frames.

Reshape data between wide and long formats in R with tidyr pivots

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Implement three reshaping helpers in `/app/solution.R` using `tidyr` (`pivot_longer()` and `pivot_wider()`) and `dplyr`. Each returns a base data.frame with default row names `1..n`. - `pivot_to_long(df, id_col)`: wide to long with exactly the columns `id_col` (type unchanged), `metric` (character, the former column names) and `value` (numeric), sorted by `id_col` then `metric`. - `pivot_to_wide(df, id_col, names_from, values_from)`: long to wide with `id_col` first, then one column per distinct `names_from` value (alphabetical), rows sorted by `id_col`. - `metric_summary(long_df)`: one row per `metric` with `mean_value` (`na.rm = TRUE`) and `n` (the non-NA count), sorted by `metric`. - Validate before reshaping: `stop()` if any named column argument is not a column of `df`. Example: ```r wide <- data.frame(id = c("a", "b"), x = c(1, 3), y = c(2, 4)) pivot_to_long(wide, "id") # id metric value # 1 a x 1 # 2 a y 2 # 3 b x 3 # 4 b y 4 long <- pivot_to_long(wide, "id") pivot_to_wide(long, "id", "metric", "value") # id x y # 1 a 1 2 # 2 b 3 4 metric_summary(long) # metric mean_value n # 1 x 2 2 # 2 y 3 2 ``` ```hint Mind the return type The pivot and summarise functions return tibbles, and `pivot_wider()` orders new columns by first appearance. Plan the explicit sort and conversion steps that turn their output into the exact shape asked for. ``` ### Clarifying Questions to Ask - In `pivot_to_wide`, can an `id_col` and `names_from` pair appear more than once, and if so should the values be aggregated or rejected? - Are all measurement columns numeric, or can some be integer, character or factor? - Should "alphabetical" follow the session locale or plain byte (C locale) order when names mix upper and lower case? ### What a Strong Answer Covers - Validating column arguments up front with a clear `stop()` message. - Pivoting every column except `id_col`, so the id keeps its type and no measurement column is assumed by name. - Enforcing the contract after the pivot: column order, row order, `metric` as character, `value` numeric, `n` as integer, and a plain data.frame with default row names. - A non-NA count for `n` that differs from the group's row count when values are missing. - Behavior for duplicates, missing combinations and mixed column types. ### Follow-up Questions - How would you handle duplicate `id_col`/`names_from` pairs in `pivot_to_wide`? - How do you preserve the original type of the id column through the round trip? - How would you pivot columns whose names encode two variables, such as `clicks_2023` and `clicks_2024`?

Overview: Write three R helpers with tidyr and dplyr: one pivots a wide data frame to long, one pivots it back to wide, and one summarizes each metric's mean and non-missing count. Tests pivot_longer and pivot_wider, deterministic column and row order, and returning clean base data frames.

General logo
General
Nov 25, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement three reshaping helpers in /app/solution.R using tidyr (pivot_longer() and pivot_wider()) and dplyr. Each returns a base data.frame with default row names 1..n.

  • pivot_to_long(df, id_col) : wide to long with exactly the columns id_col (type unchanged), metric (character, the former column names) and value (numeric), sorted by id_col then metric .
  • pivot_to_wide(df, id_col, names_from, values_from) : long to wide with id_col first, then one column per distinct names_from value (alphabetical), rows sorted by id_col .
  • metric_summary(long_df) : one row per metric with mean_value ( na.rm = TRUE ) and n (the non-NA count), sorted by metric .
  • Validate before reshaping: stop() if any named column argument is not a column of df .

Example:

wide <- data.frame(id = c("a", "b"), x = c(1, 3), y = c(2, 4))

pivot_to_long(wide, "id")
#   id metric value
# 1  a      x     1
# 2  a      y     2
# 3  b      x     3
# 4  b      y     4

long <- pivot_to_long(wide, "id")
pivot_to_wide(long, "id", "metric", "value")
#   id x y
# 1  a 1 2
# 2  b 3 4

metric_summary(long)
#   metric mean_value n
# 1      x          2 2
# 2      y          3 2

Clarifying Questions to Ask Guidance

  • In pivot_to_wide , can an id_col and names_from pair appear more than once, and if so should the values be aggregated or rejected?
  • Are all measurement columns numeric, or can some be integer, character or factor?
  • Should "alphabetical" follow the session locale or plain byte (C locale) order when names mix upper and lower case?

What a Strong Answer Covers Guidance

  • Validating column arguments up front with a clear stop() message.
  • Pivoting every column except id_col , so the id keeps its type and no measurement column is assumed by name.
  • Enforcing the contract after the pivot: column order, row order, metric as character, value numeric, n as integer, and a plain data.frame with default row names.
  • A non-NA count for n that differs from the group's row count when values are missing.
  • Behavior for duplicates, missing combinations and mixed column types.

Follow-up Questions Guidance

  • How would you handle duplicate id_col / names_from pairs in pivot_to_wide ?
  • How do you preserve the original type of the id column through the round trip?
  • How would you pivot columns whose names encode two variables, such as clicks_2023 and clicks_2024 ?