R Programming Interview Questions for 3 Years Experience
40 questions with answers for candidates with 3 years of experience — 4 easy, 32 medium, 4 hard.
What interviewers expect: 3 years experience
Three-year candidates are tested on modelling depth and production skills: tidymodels workflows, cross-validation, imbalance, feature engineering, performance tuning with data.table or dbplyr, and reproducibility with renv and Git. Expect scenario questions on model failures, stakeholder pushback and scaling pipelines to larger data. You should also be able to justify model choices to business stakeholders and reviewers.
This set is weighted towards Modelling and Machine Learning in R (9), Functions and Functional Programming (8), Data Wrangling with dplyr and tidyr (5), R Basics and Data Types (4).
tidymodels and evaluation Performance and scaling Reproducibility with renv and Git Stakeholder scenarios
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
When two vectors of different lengths are used in an operation, R repeats the shorter one to match the longer one. For example, c(1, 2, 3, 4) + c(10, 20) gives 11, 22, 13, 24. If the longer length is not a multiple of the shorter, R gives a warning but still computes. Recycling is convenient for scalars, but silent recycling of mismatched vectors is a frequent source of wrong results in analysis code.
apply() works over rows or columns of a matrix, lapply() applies a function to each element of a list and returns a list, sapply() simplifies the result to a vector or matrix when possible, vapply() is like sapply() but requires a declared output type, making it safer, and mapply() iterates over several vectors in parallel. tapply() applies a function by groups. For example, sapply(df, class) returns the class of each column.
03
In your regression, coefficient signs look wrong and standard errors are huge. What might be the problem?
This is a classic sign of multicollinearity, where predictors are highly correlated, for example total spend and online spend. The model cannot separate their effects, so coefficients become unstable. I check correlations and the variance inflation factor with car::vif(); values above 5 or 10 are a concern. Solutions are removing or combining correlated variables, using principal components or ridge regression. Prediction accuracy may be fine, but interpretation is unreliable.
plotly's ggplotly() converts an existing ggplot into an interactive chart with hover tooltips, zoom and legend toggling. ggiraph adds interactive tooltips and selection to ggplot geoms with fine control. highcharter and echarts4r wrap JavaScript charting libraries, and leaflet builds interactive maps. These outputs work in R Markdown or Quarto HTML reports and Shiny apps. For static PDF reports, standard ggplot2 is still the better choice.
05
How do you test whether two categorical variables are related in R?
Use a chi-square test of independence on a contingency table; use Fisher's exact test when expected counts are small.
tab <- table(survey$city_tier, survey$preferred_plan)
tab
res <- chisq.test(tab)
res$p.value
res$expected # check expected counts >= 5
fisher.test(tab) # for small samples
# effect size
library(rcompanion)
cramerV(tab)
06
After merging two data frames you get more rows than expected. What happened?
Extra rows after a join usually mean the key is duplicated in one or both tables, so each match multiplies rows. I check uniqueness with df %>% count(key) %>% filter(n > 1) on both sides. Then I decide whether to deduplicate, aggregate before joining or join on a composite key such as customer_id plus month. In dplyr 1.1 and later, the relationship argument, for example 'many-to-one', makes the join fail loudly when this assumption breaks.
07
What is the difference between Pearson and Spearman correlation?
Pearson correlation measures the strength of a linear relationship between two numeric variables and is sensitive to outliers. Spearman correlation is computed on ranks, so it measures monotonic relationships and is robust to outliers and non-normal data. In R, cor(x, y, method = 'spearman') and cor.test() compute them. For example, ad spend and sales with diminishing returns may show a moderate Pearson value but a high Spearman value.
08
Write code using map2() and pmap() to iterate over multiple inputs.
I use openxlsx2 or openxlsx to write a workbook with multiple sheets, formatted headers, number formats for INR, column widths, frozen panes and conditional formatting, all from R. writexl is a lightweight option for plain sheets without formatting. I create a template once with the team's preferred layout and generate the file in the scheduled script, then email or upload it to a shared drive. This removes manual formatting every day.
A Type I error is rejecting a true null hypothesis, a false positive, and its probability is the significance level alpha, usually 0.05. A Type II error is failing to reject a false null hypothesis, a false negative, with probability beta; power is 1 - beta. For example, launching a feature that does not actually help is a Type I error, while dropping a feature that really works is Type II. Larger samples reduce Type II errors.
11
Tell me about feedback you received in a code review and what you changed.
Situation: in my first quarter, a senior reviewed my R reporting script. Task: address the review comments. Action: the main feedback was that my 300-line script mixed data loading, cleaning and plotting with repeated code. I split it into small functions, added input checks and moved constants to a config file. Result: the next report took half the time to build, and I now structure every new script this way from the start.
t.test() handles one-sample, two-sample and paired tests. Welch's test, which does not assume equal variances, is the default.
# two independent groups
t.test(score ~ batch, data = students)
# paired: before vs after training
t.test(after, before, paired = TRUE)
# one-sample against a target of 30 minutes
t.test(delivery_time, mu = 30, alternative = 'greater')
res <- t.test(score ~ batch, data = students)
res$p.value; res$conf.int
data.table is a high-performance package for large tabular data. Its syntax DT[i, j, by] means filter rows with i, compute j, grouped by by. It updates columns by reference with :=, avoiding copies, and offers fast keyed joins and fread()/fwrite() for file IO. For example, DT[city == 'Delhi', .(avg_sal = mean(salary)), by = dept] filters and aggregates in one step. It is popular for datasets with tens of millions of rows.
14
You are asked to forecast daily demand for the Diwali season. How do you approach it?
I gather at least two or three years of daily history, since festive peaks happen once a year and Diwali moves across October and November. I add holiday regressors for Diwali, Dussehra and sale events rather than relying on calendar seasonality alone. I compare models like ETS, ARIMA with regressors and prophet in fable, validating on past festive seasons. I report prediction intervals and review with business teams for planned promotions or stock limits.
15
Code reviews show inconsistent R code style across the team. How would you standardise it?
I would adopt the tidyverse style guide as the team standard, then automate it rather than relying on reviewers. styler reformats code automatically, including an RStudio add-in, and lintr flags issues such as long lines, unused variables and inconsistent naming. I add lintr to a pre-commit hook or a GitHub Actions check so pull requests are checked automatically. A short template for new scripts and projects helps new joiners follow the same structure.
16
Describe a time you found a data quality issue in your analysis.
Situation: while preparing a monthly revenue dashboard, totals were 8 percent higher than finance figures. Task: find the cause before the review meeting. Action: I traced row counts after each step in my R script and found a join on customer ID that duplicated rows because some customers had two active addresses. I deduplicated the address table and added a row-count check. Result: numbers matched finance, and the check now runs in every refresh.
17
Your function fails with 'the condition has length > 1' when given a vector. What is wrong?
An if statement can only check a single TRUE or FALSE value, and since R 4.2 a longer condition is an error. The function was written for one value but received a vector. I would replace if with a vectorized alternative such as ifelse(), dplyr::if_else() or case_when(). If the function is truly meant for single values, I validate the input length with stopifnot(length(x) == 1) or apply it over elements with purrr::map().
18
What tools does R offer for time series forecasting?
The forecast package provides auto.arima(), ets() for exponential smoothing and easy plotting of forecasts with intervals. The newer tidyverts family, with tsibble for time-series data frames, fable for models and feasts for features and decomposition, works with tidy data and fits many series at once. prophet handles strong seasonality and holidays. Typical steps are visualizing, decomposing trend and seasonality, fitting candidates and comparing accuracy on a holdout period.
Overfitting happens when a model learns noise in the training data, so it performs very well on training data but poorly on new data. Signs are a large gap between training and validation scores. Prevention includes using simpler models, regularization such as lasso or ridge, cross-validation for tuning, limiting tree depth, getting more data and removing leaky or irrelevant features. Underfitting is the opposite: the model is too simple to capture the pattern.
20
Describe a disagreement with a teammate about a technical approach.
Situation: a teammate wanted to build our reporting pipeline in Excel macros, while I preferred R scripts. Task: agree on an approach quickly. Action: instead of arguing, we listed requirements together: refresh frequency, data size and who would maintain it. I built a small R prototype in a day to compare. Result: we chose R for the pipeline and kept an Excel output for users, and my teammate later helped improve the formatting.
21
What are the differences between S3, S4 and R6 classes?
S3 is R's simplest object system: an object is a list with a class attribute, and generic functions like print() dispatch on it through UseMethod(). S4 adds formal class definitions with setClass(), typed slots and validity checks, and is common in Bioconductor. R6, from a package, provides reference semantics with mutable objects and encapsulated methods, similar to classes in Python or Java, and is used inside Shiny. Most analysis code needs only S3.
A closure is a function that remembers the environment in which it was created. A function factory is a function that returns such functions. For example, power <- function(exp) function(x) x^exp; square <- power(2) creates a function that remembers exp = 2. They are useful for creating families of related functions, counters and memoised functions. Because of lazy evaluation, call force(exp) inside the factory so the value is captured immediately.
23
Walk me through an end-to-end machine learning project you have done in R.
Situation: a lending team wanted to reduce early loan defaults. Task: build a default risk score. Action: I cleaned two years of loan data with dplyr, engineered features like EMI to income ratio with recipes, compared logistic regression and ranger in tidymodels using 5-fold cross-validation and chose logistic regression for interpretability with AUC 0.78. Result: the score was used in a pilot, flagging 60 percent of defaulters in the riskiest 20 percent of applicants.
24
How do you build a logistic regression model for churn in R?
Tidy data follows three rules: each variable is a column, each observation is a row and each type of observational unit forms a table. For example, a sales sheet with separate columns for Jan, Feb and Mar is not tidy, because month is a variable spread across columns. Reshaping it into month and sales columns makes it tidy. Tidy data works directly with dplyr, ggplot2 and modelling functions, reducing reshaping effort later.
R is strongest for statistics, exploratory analysis, visualization and reproducible reporting, with mature packages for biostatistics, econometrics and survey analysis. Python is a general-purpose language that is stronger for production software, deep learning and web integration. Many teams use both: R for analysis and reporting, Python for pipelines and deployment. In an interview, avoid language wars and explain that the choice depends on the team's stack, the problem and who maintains the code.
28
How do you add labels and annotations to a ggplot chart?
A pure function always returns the same output for the same inputs and has no side effects, such as modifying global variables, writing files or printing. Pure functions are easy to test, reuse, cache and run in parallel, because they do not depend on hidden state. In data pipelines, I keep transformations pure, taking a data frame and returning a new one, and isolate side effects such as reading and writing in a few clearly named functions.
30
How do you apply the same transformation to many columns in dplyr?
across() applies one or more functions to a set of columns selected with tidyselect helpers.
df %>%
mutate(across(where(is.character), str_trim)) %>%
mutate(across(starts_with('amt_'), ~ round(.x, 2)))
df %>%
group_by(region) %>%
summarise(across(c(sales, profit),
list(mean = mean, max = max),
.names = '{.col}_{.fn}'))
31
Salary data has a few extreme values that distort averages. How do you handle them?
First I investigate whether they are data errors, such as an extra zero, or genuine high earners. I flag outliers with the IQR rule, values beyond Q1 - 1.5 IQR or Q3 + 1.5 IQR, or with percentiles. Errors I fix or remove with documentation. Genuine values I keep, but I report the median alongside the mean, or winsorize at the 1st and 99th percentiles for modelling. The choice depends on the business question.
purrr's map() applies a function to each element of a list or vector and always returns a list. Typed variants return specific types: map_dbl(), map_chr(), map_lgl() and map_int(), and they error if a result has the wrong type, which is safer than sapply(). map2() iterates over two inputs, pmap() over many, and walk() is used for side effects like saving files. Formula shortcuts such as ~ .x * 2 keep code short.
left_join() keeps all rows of the left table and adds matching columns from the right, inner_join() keeps only matching rows, right_join() keeps all rows of the right table and full_join() keeps all rows from both, filling NA where there is no match. Keys are given with by = join_by(customer_id) or by = c('id' = 'cust_id') for different names. Left joins are most common when enriching a fact table with lookup details.
34
You need month-over-month sales growth for each product. How do you calculate it in R?
I first aggregate to one row per product and month with group_by() and summarise(). Then I group by product, arrange by month and use mutate(growth = (sales - lag(sales)) / lag(sales) * 100). The first month for each product becomes NA, which is correct. I make sure months with zero sales exist using tidyr::complete(), otherwise lag() compares non-consecutive months. Finally I round and format growth for reporting.
35
Business users do not trust your gradient boosting model because it is a black box. What do you do?
I explain both global and individual behaviour. Globally, I show variable importance and partial dependence plots, using DALEX or the vip package, to show how key features affect predictions. For individual cases I use SHAP values, for example through the shapviz or fastshap packages, so a manager can see why a customer was flagged. I compare against a simple logistic model and walk users through real examples they know.
36
What is type coercion in R and how can it cause bugs?
Coercion is the automatic conversion of values to a common type when they are combined in an atomic vector. The order is logical, then integer, then double, then character. So c(1, 'a', TRUE) becomes the character vector '1', 'a', 'TRUE'. Explicit conversion uses as.numeric(), as.character() and similar functions. A common bug is a numeric column with one stray text value, which turns the whole column into character and breaks calculations.
A recursive function calls itself with a smaller input and needs a base case.
fact <- function(n) {
if (n <= 1) return(1)
n * fact(n - 1)
}
fact(5) # 120
fib <- function(n) {
if (n <= 2) return(1)
fib(n - 1) + fib(n - 2)
}
fib(10) # 55
# vectorized and efficient alternative
factorial(5); cumprod(1:5)
39
How do you calculate ROC AUC and plot an ROC curve in R?
I would extract the logic into well-named functions with arguments for the parts that differ, then move them into one shared file loaded with source() or, better, a small internal R package. A package gives documentation with roxygen2, tests with testthat and versioning, so every script uses the same tested logic. Fixing a bug then happens in one place. I would migrate the scripts gradually and compare outputs to confirm nothing changed.
Frequently asked questions
What is asked in R Programming interviews for 3 years of experience?
Three-year candidates are tested on modelling depth and production skills: tidymodels workflows, cross-validation, imbalance, feature engineering, performance tuning with data.table or dbplyr, and reproducibility with renv and Git. Expect scenario questions on model failures, stakeholder pushback and scaling pipelines to larger data. You should also be able to justify model choices to business stakeholders and reviewers.
How many questions should I practise before a R Programming interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 3 years of experience?
Focus first on tidymodels and evaluation, Performance and scaling, Reproducibility with renv and Git, Stakeholder scenarios.