Custom Function Development in R

Instruction: Explain the process of writing and optimizing a custom function in R for a specific data analysis task.

Context: This question tests the candidate's ability to extend R's functionality through custom functions, a key skill for advanced data analysis.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

Define the input/output contract before optimizing. This reference function returns a trailing mean of k observations, with incomplete windows left missing. It validates the window and exposes a missing-value policy.

trailing_mean <- function(x, k, na_rm = FALSE) { stopifnot(is.numeric(x), is.null(dim(x)), length(k) == 1L, is.finite(k), k >= 1, k == floor(k), is.logical(na_rm), length(na_rm) == 1L, !is.na(na_rm)) out <- rep(NA_real_, length(x)) if...

Related Questions