R programming interview questions, from vectors to models and Shiny
R programming interview questions test whether you can wrangle, model and explain data in R: vectors and recycling, NA handling, the difference between [ and [[, factors, the apply family, dplyr and tidyr pipelines, ggplot2, and fitting and checking models such as lm and glm. Senior and data science interviews add functions and environments, S3 classes, performance, reproducibility with renv and Quarto, and Shiny. Strong answers pair correct code with a clear statistical explanation.
By Evin JohnPublished 7 min read
How R shows up in interviews
R is common in biostatistics, pharma and clinical research, academia, public health, economics, insurance and analytics teams that grew out of statistics. Interviews usually test R alongside statistics, so a question like "fit a model to this data" is followed by "how do you know it is any good?". Some companies are tidyverse-first, others prefer base R or data.table, and many interviewers accept either if you can explain your choice. If the role also uses Python, expect to be asked how you would do the same task in pandas; the pandas interview questions cover that side.
- ScreenShort questions on data types, NA, indexing and common functions, sometimes "what does this return?" on a snippet.
- Live or take-home analysisClean a messy dataset, summarize it, make a chart and fit a simple model, often in an R Markdown or Quarto notebook.
- Statistics discussionInterpret output from lm or glm, check assumptions, and explain results to a non-statistician.
- Senior or engineering roundPackage structure, testing with testthat, reproducibility, performance and production use such as Shiny apps or scheduled reports.
Fundamentals: types, NA and vectors
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the main data structures in R? | Basics | Atomic vectors (one type), lists (any types), matrices and arrays, data frames as lists of equal-length columns, and factors for categories |
| What is the difference between NA, NULL and NaN? | Missing values | NA is a missing value of a type, NULL is the absence of an object (length zero), NaN is an undefined number such as 0/0 |
| What is vector recycling, and when is it dangerous? | Vectorization | Shorter vectors repeat to match longer ones; it hides bugs when lengths do not divide evenly or were not meant to differ |
| Why is vectorized code usually faster than a for loop in R? | Performance | The loop runs in compiled code instead of the interpreter; loops are fine when preallocated and when each step depends on the last |
| What does type coercion do when you combine values with c()? | Types | Everything becomes the most flexible type: logical to integer to double to character |
| How do you check the structure of an unfamiliar object? | Exploration | str(), class(), typeof(), summary() and head(), and glimpse() in dplyr |
| What is the difference between = and <- for assignment? | Style | Both assign at top level; <- is the common style, = is also used for function arguments, which is why many style guides keep them separate |
x <- c(1, 2, NA, 4)
mean(x) # NA
mean(x, na.rm = TRUE) # 2.333333
length(NULL) # 0
c(1, 2, 3, 4) + c(10, 20) # 11 22 13 24 (recycling)
f <- factor(c("10", "5", "20"))
as.numeric(f) # 1 3 2 (level codes; levels sort as text: "10" "20" "5")
as.numeric(as.character(f)) # 10 5 20Indexing, lists and the apply family
- What is the difference between [ and [[ on a list? Single brackets return a smaller list; double brackets return the element itself.
lst$nameis shorthand forlst[["name"]]with partial matching on names. - How do you select rows of a data frame by a condition in base R?
df[df$amount > 100, ], remembering the comma, and that NA in the condition produces rows of NA unless you usewhich()orsubset(). - What is the difference between lapply, sapply and vapply? lapply always returns a list; sapply simplifies when it can, which can surprise you; vapply simplifies to a declared type and fails loudly if the result does not match.
- When would you use mapply or Map? When a function needs to walk several vectors in parallel, such as pairs of start and end dates.
- What does drop = FALSE do? Keeps a one-column selection as a data frame or matrix instead of dropping it to a vector, which avoids bugs in functions that expect columns.
- Why are factors sometimes a problem, and when are they useful? Converting them to numbers returns level codes, and unused levels hang around; they are useful for modeling and controlling the order of categories in plots.
lst <- list(a = 1:3, b = "x")
lst["a"] # a list with one element named a
lst[["a"]] # the integer vector 1 2 3
lst$a # same as lst[["a"]]
nums <- list(c(1, 2), c(3, 4, 5))
vapply(nums, mean, numeric(1)) # 1.5 4.0
sapply(nums, range) # simplifies to a 2 x 2 matrixData wrangling with dplyr, tidyr and data.table
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Walk me through the main dplyr verbs. | Tidyverse fluency | filter, select, mutate, arrange, summarise and group_by, each doing one job and chained with a pipe |
| What is the difference between |> and %>%? | Pipes | |> is the native pipe in recent R versions, %>% comes from magrittr and supports a few extra features such as the dot placeholder |
| How do left_join, inner_join and anti_join differ? | Joins | Keep all left rows, keep only matches, or keep left rows without a match, which is handy for finding missing records |
| A join suddenly returns more rows than the left table. Why? | Data quality | Duplicate keys on the right side; check with count() on the key before joining |
| How do you reshape data from wide to long? | tidyr | pivot_longer to stack measured columns into name and value columns, pivot_wider for the reverse |
| When would you choose data.table over dplyr? | Performance | Very large data in memory, fast grouped operations and updates by reference, at the cost of a terser syntax |
| How do you handle dates in R? | Dates | Date and POSIXct types, lubridate for parsing and arithmetic, and explicit time zones |
library(dplyr)
sales |>
filter(!is.na(amount)) |>
group_by(region) |>
summarise(
total = sum(amount),
orders = n(),
avg = mean(amount),
.groups = "drop"
) |>
arrange(desc(total))Visualization and statistics
- Explain the grammar of graphics in ggplot2. Data, aesthetic mappings, geoms, scales, facets and themes layered with +, so a chart is built from parts rather than picked from a menu.
- When would you use facet_wrap instead of color to compare groups? When there are many groups or the lines overlap so much that color stops helping.
- How do you read the output of summary(lm(...))? Coefficients with standard errors and p-values, residual standard error, R-squared and the F-test, and why a small p-value does not mean a large or useful effect.
- How do you check whether a linear model is appropriate? Residual plots for patterns and changing spread, a Q-Q plot, influential points and whether the relationship is plausibly linear.
- When do you use glm instead of lm? When the outcome is not continuous and roughly normal, such as yes or no outcomes with a binomial family or counts with Poisson.
- How do you interpret a coefficient in a logistic regression? As a change in log-odds; exponentiate to get an odds ratio, and be careful explaining odds to non-statisticians.
- Why call set.seed? So random sampling, simulation and train-test splits give the same results when someone reruns the analysis.
model <- lm(mpg ~ wt + hp, data = mtcars)
summary(model) # coefficients, standard errors, R-squared
confint(model) # confidence intervals for each coefficient
par(mfrow = c(2, 2))
plot(model) # residuals, Q-Q, scale-location, leverage
logit <- glm(am ~ wt, data = mtcars, family = binomial)
exp(coef(logit)) # odds ratiosSenior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is lazy evaluation in R? | Language internals | Arguments are evaluated only when used, which allows defaults that depend on other arguments and some tidyverse tricks |
| How does R find a variable inside a function? | Scoping | Lexical scoping through environments: the function's own, then where it was defined, up to the global and package environments |
| What is copy-on-modify, and why does it matter for speed? | Memory | Changing an object that is shared makes a copy, so growing a vector in a loop copies it repeatedly; preallocate instead |
| How does S3 dispatch work? | OOP | A generic such as print calls UseMethod, which looks for print.classname based on the class attribute, falling back to the default |
| When would you choose S4 or R6 over S3? | OOP trade-offs | S4 for formal classes and validity checks (common in Bioconductor), R6 for mutable objects with reference semantics |
| How do you make an analysis reproducible for a colleague? | Reproducibility | A project folder, renv to lock package versions, a Quarto or R Markdown report, set.seed, and no hard-coded local paths |
| An R script that ran in minutes now takes hours. How do you investigate? | Profiling | Profile with profvis or Rprof, look for growing objects, row-by-row loops and repeated reads, then vectorize or move to data.table |
| How does reactivity work in Shiny? | Shiny | Inputs feed reactive expressions and outputs; Shiny reruns only what depends on a changed input, and isolate or eventReactive control when that happens |
| How do you test R code? | Quality | testthat for functions, small fixtures, and checks on edge cases such as NA, empty data and unexpected types |
Fictional example
- At a regional health insurer, I was asked why claim costs had jumped in one quarter. My first dplyr summary showed a sharp rise in average cost per member. Before reporting it, I checked counts by month and found a group of claims that appeared twice: a left join on member ID had duplicated rows because a reference table listed some members under two plans. I fixed the join to use member ID and plan date, added a check that row counts did not change after joining, and the jump shrank to a small seasonal rise. I wrote the check into our shared helper functions so the next analysis would catch it automatically. Since then I count keys before every join.
A three-week R practice plan
- Week 1: types, NA, indexing and the apply family in base R; answer twenty "what does this return?" snippets without running them, then check.
- Week 2: dplyr, tidyr and joins on a messy public dataset, then three ggplot2 charts you could explain to a manager.
- Week 3, first half: lm and glm with diagnostics, and a two-minute plain-language explanation of each model.
- Week 3, second half: a short Quarto report with renv, a few testthat tests and one function rewritten for speed.
R often sits beside SQL and other analysis languages. The SQL interview questions cover the queries that usually feed an R analysis, MATLAB interview questions cover the engineering side of numerical work, and Looker interview questions show how analysts publish metrics in a BI tool. For the role around the language, see the data analyst guide and the data scientist guide.
Explaining a model's output out loud is a separate skill from writing the code. In practice sessions, Natively, an AI interview assistant on Mac and Windows, keeps a transcript of how you talked through a regression summary so you can tighten it. It can also read R output or a problem from a screenshot and suggest a hint or an outline, and on Pro or the free trial bring in your résumé and the job description. Your practice history and notes stay saved.
Questions people ask
What are common R programming interview questions?
The difference between NA, NULL and NaN, how recycling works, [ versus [[ on a list, why factors can surprise you, lapply versus sapply versus vapply, the main dplyr verbs and joins, and how to read and check an lm or glm model.
Should I use base R or the tidyverse in an interview?
Either is usually fine if your code is correct and you can explain it. Many teams work tidyverse-first, some prefer base R or data.table. Mention the trade-offs and match the team's style if you know it.
How much statistics is in an R interview?
Usually a fair amount for analyst and data science roles: fitting and interpreting linear and logistic models, checking assumptions with diagnostics, and explaining results to people who are not statisticians.
How do I prepare for an R take-home assignment?
Practice a full mini-analysis in a Quarto or R Markdown notebook: clean a messy dataset, summarize it, make two clear charts, fit a simple model with diagnostics, and write short conclusions with limits.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
