Vectorize a Slow Group-Stats Script in R: Group Summary, Running Total and Moving Average

Quick Overview

Rewrite a loop-based R script as vectorized code that computes per-group count, mean and sample standard deviation, a within-group running total in the original row order, and a trailing moving average. It tests grouped aggregation, order-preserving cumulative sums and prefix-sum windows in R.

Vectorize a Slow Group-Stats Script in R: Group Summary, Running Total and Moving Average

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

A slow script computes group statistics with explicit loops. Rewrite it in `/app/solution.R` as vectorized R code that implements exactly the three functions below. Only correctness is graded. - `compute_group_stats(df, group_col, value_col)`: return a data.frame with columns `group`, `n` (integer), `mean` and `sd` (sample standard deviation with denominator `n - 1`, `NA` for a group with a single row), one row per group, sorted ascending by group, with row names reset. - `add_running_total(df, group_col, value_col, order_col)`: return `df` in its original row order plus a numeric column `running_total`, the cumulative sum of `value_col` within each group taken in ascending `order_col` order, with row names reset. - `moving_average(x, k)`: return a vector the same length as `x` with `out[i] = mean(x[(i-k+1):i])` for `i >= k` and `NA_real_` for the first `k-1` positions. If `k < 1` or `k` is not a length-1 numeric, `moving_average` must call `stop()`. Example: ```r df <- data.frame(g = c("b", "a", "a", "b"), v = c(10, 1, 3, 20), t = c(2, 1, 2, 1)) compute_group_stats(df, "g", "v") # group n mean sd # 1 a 2 2 1.414214 # 2 b 2 15 7.071068 add_running_total(df, "g", "v", "t")$running_total # [1] 30 1 4 20 # same original row order moving_average(c(1, 2, 3, 4), 2) # [1] NA 1.5 2.5 3.5 ``` In group `b`, row 4 (`t = 1`) comes first, so its running total is 20, and row 1 (`t = 2`) gets 20 + 10 = 30. ```hint Getting rows back Sorting is needed only so the cumulative sum runs in `order_col` order. Decide what you keep from the sort so every result can be written back to its original row. ``` ```hint Windows in one pass A window sum is the difference of two cumulative sums. Check what that difference does to the windows after a missing value in `x`. ``` ### Constraints & Assumptions - All `*_col` arguments are length-1 character column names present in `df`. - `df` may be a data.frame or a data.table. `data.table` is available but not required; base R is enough. - Only correctness is graded, but each function should avoid per-row R loops. ### Clarifying Questions to Ask - How should rows that tie on `order_col` within a group be ordered for the running total? - Can the group or value columns contain `NA`, and what should those rows get? - Should a non-whole `k` such as 2.5 be rejected or truncated? - Should `group` in the output keep the input column's type (factor, number) or become character? ### What a Strong Answer Covers - Computes per-group count, mean and sample standard deviation with grouped primitives, with `NA` for singletons, groups sorted and row names reset. - Runs the cumulative sum within groups in `order_col` order and writes every value back to its original row. - Computes the moving average in linear time with the exact `NA` pattern for the first `k-1` positions and for `k` larger than the input. - Validates `k` so that no comparison is evaluated on a vector or on `NA`. - Names the edge cases: ties in the order column, `NA` in groups or values, precision of prefix sums. ### Follow-up Questions - How would a `data.table` implementation of `add_running_total` preserve original row order? - When does parallelizing these operations actually help? - What goes wrong with a prefix-sum moving average when `x` contains `Inf` or values of very different magnitude?

Overview: Rewrite a loop-based R script as vectorized code that computes per-group count, mean and sample standard deviation, a within-group running total in the original row order, and a trailing moving average. It tests grouped aggregation, order-preserving cumulative sums and prefix-sum windows in R.

Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

A slow script computes group statistics with explicit loops. Rewrite it in /app/solution.R as vectorized R code that implements exactly the three functions below. Only correctness is graded.

  • compute_group_stats(df, group_col, value_col) : return a data.frame with columns group , n (integer), mean and sd (sample standard deviation with denominator n - 1 , NA for a group with a single row), one row per group, sorted ascending by group, with row names reset.
  • add_running_total(df, group_col, value_col, order_col) : return df in its original row order plus a numeric column running_total , the cumulative sum of value_col within each group taken in ascending order_col order, with row names reset.
  • moving_average(x, k) : return a vector the same length as x with out[i] = mean(x[(i-k+1):i]) for i >= k and NA_real_ for the first k-1 positions. If k < 1 or k is not a length-1 numeric, moving_average must call stop() .

Example:

df <- data.frame(g = c("b", "a", "a", "b"), v = c(10, 1, 3, 20), t = c(2, 1, 2, 1))

compute_group_stats(df, "g", "v")
#   group n mean       sd
# 1     a 2    2 1.414214
# 2     b 2   15 7.071068

add_running_total(df, "g", "v", "t")$running_total
# [1] 30  1  4 20   # same original row order

moving_average(c(1, 2, 3, 4), 2)
# [1]  NA 1.5 2.5 3.5

In group b, row 4 (t = 1) comes first, so its running total is 20, and row 1 (t = 2) gets 20 + 10 = 30.

Constraints & Assumptions

  • All *_col arguments are length-1 character column names present in df .
  • df may be a data.frame or a data.table. data.table is available but not required; base R is enough.
  • Only correctness is graded, but each function should avoid per-row R loops.

Clarifying Questions to Ask Guidance

  • How should rows that tie on order_col within a group be ordered for the running total?
  • Can the group or value columns contain NA , and what should those rows get?
  • Should a non-whole k such as 2.5 be rejected or truncated?
  • Should group in the output keep the input column's type (factor, number) or become character?

What a Strong Answer Covers Guidance

  • Computes per-group count, mean and sample standard deviation with grouped primitives, with NA for singletons, groups sorted and row names reset.
  • Runs the cumulative sum within groups in order_col order and writes every value back to its original row.
  • Computes the moving average in linear time with the exact NA pattern for the first k-1 positions and for k larger than the input.
  • Validates k so that no comparison is evaluated on a vector or on NA .
  • Names the edge cases: ties in the order column, NA in groups or values, precision of prefix sums.

Follow-up Questions Guidance

  • How would a data.table implementation of add_running_total preserve original row order?
  • When does parallelizing these operations actually help?
  • What goes wrong with a prefix-sum moving average when x contains Inf or values of very different magnitude?