Write R utility functions with exact error messages and a testthat suite

Quick Overview

Implement four small R utilities that validate their inputs with exact error messages, then write a testthat suite for every success path and error branch. Tests validation order, NA and type edge cases, floating-point comparisons and precise expect_error assertions.

Write R utility functions with exact error messages and a testthat suite

Role: Data Scientist

Category: Software Engineering Fundamentals

Difficulty: easy

Interview Round: Other

Implement four utility functions in `/app/solution.R` that validate their inputs and raise the exact error messages below. Then write a `testthat` suite that covers the happy paths and every error condition using `expect_equal` and `expect_error`. The messages must match exactly so the regex assertions pass. - `safe_divide(numerator, denominator)` returns `numerator / denominator`. It calls `stop("inputs must be numeric")` if either argument is non-numeric and `stop("division by zero")` if `denominator == 0`. - `summary_stats(x)` returns a named list with `n`, `mean`, `median` and `sd`, computed after removing `NA` values (`n` is the non-NA count). It calls `stop("x must be numeric")` if `x` is not numeric and `stop("x must be non-empty")` if `x` is empty or all `NA`. - `normalize(x)` returns `(x - mean(x)) / sd(x)` using the sample sd from base `sd()`. It calls `stop("x must be numeric")` for non-numeric input, `stop("need at least two values")` if `length(x) < 2`, and `stop("standard deviation is zero")` if `sd(x) == 0`. - `count_words(s)` returns the integer count of whitespace-separated words, with `0` for an empty or whitespace-only string. It calls `stop("s must be a character scalar")` if `s` is not a length-1 character vector. ```r safe_divide(10, 2) # 5 summary_stats(c(1, 2, NA, 4)) # list(n = 3, mean = 2.333..., median = 2, sd = 1.528...) normalize(c(1, 2, 3)) # -1, 0, 1 count_words(" hello world ") # 2 # error assertions expect_error(safe_divide(1, 0), "division by zero") expect_error(normalize(c(5, 5)), "standard deviation is zero") ``` ```hint Reaching each branch For every `stop()`, pick a test input that reaches it without tripping an earlier check. Look at the type R gives a vector written as `c(NA, NA)`. ``` ```hint Message matching Read how `expect_error()` uses its second argument. Decide whether a partial match is strict enough for "messages must match exactly". ``` ### Constraints & Assumptions - Only base R, `stats` and `testthat` are available. - `/app/solution.R` defines the functions only, with no top-level side effects, so the tests live in a separate file that sources it. - Numeric inputs to `safe_divide` are scalars. ### What a Strong Answer Covers - Validation order in each function, so every documented message is reachable and raised with the exact text. - Correct results on the examples, including `NA` removal in `summary_stats` and the sample sd in `normalize`. - `count_words` behavior on repeated, leading and trailing whitespace, and an integer return type. - A test file with at least one `expect_equal` per success path and one `expect_error` per error branch, using inputs that reach the intended branch. - Floating-point comparisons with a sensible tolerance and message assertions that cannot pass on the wrong error. ### Follow-up Questions - How would you assert on the shape of the `summary_stats` return value? - Why match the error message instead of expecting any error at all? - How would you test for an error condition class instead of the message text, and when is that the better choice? - What should `normalize` and `count_words` do when the input contains `NA`, and how would you pin that down in tests?

Overview: Implement four small R utilities that validate their inputs with exact error messages, then write a testthat suite for every success path and error branch. Tests validation order, NA and type edge cases, floating-point comparisons and precise expect_error assertions.

Nov 25, 2026
easyData ScientistOtherSoftware Engineering Fundamentals
0
0

Implement four utility functions in /app/solution.R that validate their inputs and raise the exact error messages below. Then write a testthat suite that covers the happy paths and every error condition using expect_equal and expect_error. The messages must match exactly so the regex assertions pass.

  • safe_divide(numerator, denominator) returns numerator / denominator . It calls stop("inputs must be numeric") if either argument is non-numeric and stop("division by zero") if denominator == 0 .
  • summary_stats(x) returns a named list with n , mean , median and sd , computed after removing NA values ( n is the non-NA count). It calls stop("x must be numeric") if x is not numeric and stop("x must be non-empty") if x is empty or all NA .
  • normalize(x) returns (x - mean(x)) / sd(x) using the sample sd from base sd() . It calls stop("x must be numeric") for non-numeric input, stop("need at least two values") if length(x) < 2 , and stop("standard deviation is zero") if sd(x) == 0 .
  • count_words(s) returns the integer count of whitespace-separated words, with 0 for an empty or whitespace-only string. It calls stop("s must be a character scalar") if s is not a length-1 character vector.
safe_divide(10, 2)                 # 5
summary_stats(c(1, 2, NA, 4))      # list(n = 3, mean = 2.333..., median = 2, sd = 1.528...)
normalize(c(1, 2, 3))              # -1, 0, 1
count_words("  hello   world ")    # 2

# error assertions
expect_error(safe_divide(1, 0), "division by zero")
expect_error(normalize(c(5, 5)), "standard deviation is zero")

Constraints & Assumptions

  • Only base R, stats and testthat are available.
  • /app/solution.R defines the functions only, with no top-level side effects, so the tests live in a separate file that sources it.
  • Numeric inputs to safe_divide are scalars.

What a Strong Answer Covers Guidance

  • Validation order in each function, so every documented message is reachable and raised with the exact text.
  • Correct results on the examples, including NA removal in summary_stats and the sample sd in normalize .
  • count_words behavior on repeated, leading and trailing whitespace, and an integer return type.
  • A test file with at least one expect_equal per success path and one expect_error per error branch, using inputs that reach the intended branch.
  • Floating-point comparisons with a sensible tolerance and message assertions that cannot pass on the wrong error.

Follow-up Questions Guidance

  • How would you assert on the shape of the summary_stats return value?
  • Why match the error message instead of expecting any error at all?
  • How would you test for an error condition class instead of the message text, and when is that the better choice?
  • What should normalize and count_words do when the input contains NA , and how would you pin that down in tests?