Intermediate R: Moving Beyond Basic Scripts to Scalable Code

Once you are comfortable importing data, writing basic for loops, subsetting data frames, and building simple plots in R, you hit a familiar crossroads. Scripts that worked fine on a few hundred rows start running slowly on hundreds of thousands, copy-pasted code becomes hard to maintain, and subtle bugs emerge from variable scoping, type coercion, or missing values (NA). Intermediate R is the stage where you shift from making code work once to making it clean, fast, modular, and dependable across real analytical projects.

At this level, mastery comes from understanding how R evaluates expressions, how to replace repetitive code with functions and functional tools, and how to handle tabular data and errors deliberately.

1. Vectorization and Avoiding Slow Loops

Beginners often write for loops to step through every element of a vector or row of a data frame while growing an output object piece by piece (out <- c(out, ...)). In R, growing an object inside a loop repeatedly reallocates memory and slows execution dramatically.

Vectorization pushes iteration down into fast, compiled C or C++ routines underneath R’s base functions:

R

# Slower: growing a vector inside a loop
out <- numeric(length(x))
for (i in seq_along(x)) {
  out[i] <- (x[i] - mean(x)) / sd(x)
}

# Faster and cleaner: vectorized arithmetic
z <- (x - mean(x)) / sd(x)

Notice also that computing mean(x) and sd(x) once outside the loop avoids recalculating summary statistics on every iteration. When loops are appropriate—such as sequential simulations where step t depends on step t - 1—pre-allocating the output vector (numeric(n), vector("list", n)) keeps memory behavior predictable.

2. Writing Clean, Reusable Functions

As soon as you copy and paste a block of code and change one or two arguments, it belongs in a function. Good intermediate R functions are small, have clear names, validate inputs early, and avoid unintended side effects.

R

summarize_metric <- function(df, group_col, value_col, na.rm = TRUE) {
  stopifnot(is.data.frame(df), is.logical(na.rm), length(na.rm) == 1L)

  df |>
    dplyr::group_by(.data[[group_col]]) |>
    dplyr::summarise(
      n = dplyr::n(),
      mean_val = mean(.data[[value_col]], na.rm = na.rm),
      median_val = stats::median(.data[[value_col]], na.rm = na.rm),
      .groups = "drop"
    )
}

Key habits that separate intermediate functions from quick throwaway snippets include:

  • Explicit namespace calls (pkg::fun()): Makes dependencies obvious and prevents collisions when multiple packages define functions with the same name (such as filter() or select()).
  • Argument defaults and validation: Checking inputs with stopifnot() or cli::cli_abort() surfaces clear errors close to the cause rather than deep inside a downstream call.
  • No hidden global mutations: Avoid modifying global variables inside functions unless explicitly designing a stateful utility; returning a clean value makes code easier to test and reason about.

3. Functional Programming: apply and purrr

Functions in R are first-class objects—you can pass a function as an argument to another function. Instead of writing boilerplate loops over lists, columns, or model fits, functional tools apply a function across elements and return structured results.

  • Base R apply family: lapply() always returns a list, sapply() attempts to simplify results to a vector or matrix (which can be risky in programmatic code when lengths vary), and vapply() enforces a strict output template—making vapply() safer in production scripts.
  • purrr map functions: Functions like map(), map_dbl(), map_chr(), map_dfr() / list_rbind(), and map2() / pmap() offer consistent type-safe return types and clean anonymous function syntax (\(x) ... or formula shorthand).

R

library(purrr)

# Fit linear models across multiple outcome formulas stored in a list
formulas <- list(
  mpg ~ wt,
  mpg ~ wt + hp,
  mpg ~ wt + hp + drat
)

models <- map(formulas, \(f) lm(f, data = mtcars))
r2_values <- map_dbl(models, \(m) summary(m)$r.squared)

4. Data Manipulation, Factors, and Tidy Pipelines

Real analytical pipelines spend most of their time reshaping tables, joining datasets, handling dates, and cleaning categorical variables. At the intermediate level, three areas deserve special care:

  • Relational joins and row granularity: Always check row counts and key uniqueness before and after left_join(), inner_join(), or anti_join(). A duplicate key on a lookup table silently multiplies rows and inflates sums or averages.
  • Factors (forcats): Categorical variables stored as plain character strings sort alphabetically in plots and tables. Converting them to ordered factors lets you control reference levels in regression models and display order in charts.
  • Missing values (NA): R propagates NA through arithmetic and comparisons (NA == NA evaluates to NA, not TRUE). Use is.na(), coalesce(), or explicit na.rm handling rather than guessing how missing cells behave.

5. Lexical Scoping, Environments, and Debugging

R uses lexical scoping: if a symbol is not found inside a function’s local environment, R looks in the environment where the function was defined (typically a package namespace or the global environment), not where it was called. Understanding this prevents surprises when creating closures or helper factories, and reminds you not to rely on accidental global variables that might not exist in a fresh R session.

When things do go wrong, intermediate R users move beyond print() spam to structured diagnostics:

  • Inspecting call stacks and errors: Use traceback() after an error to see the exact call sequence, browser() or RStudio/Positron breakpoints to step through execution interactively, and tryCatch() when an external read, API call, or model fit might fail on a subset of inputs without crashing an entire batch run.
  • Benchmarking and profiling: Use bench::mark() or system.time() to compare two implementations on realistic data sizes, and profvis or Rprof() to spot which line actually consumes CPU time or memory.

Summary

Intermediate R is less about memorizing obscure syntax and more about building reliable engineering habits: vectorizing operations, writing focused functions with explicit inputs and outputs, using functional mapping cleanly, verifying joins and NA behavior, and diagnosing bottlenecks or errors systematically. Practicing these patterns on a real multi-script project will make your R code faster, easier to maintain, and ready for larger datasets and team collaboration.