Skip to content

Data Scientist (R) Interview Questions & Answers

40 questions for Data Scientist (R) interviews — 4 easy, 31 medium, 5 hard.

About the Data Scientist (R) role

A Data Scientist using R builds predictive models for churn, risk, demand and pricing, from feature engineering to evaluation and deployment. They use tidymodels, glmnet, ranger and forecasting packages, explain models to business teams and monitor them after launch. The role combines statistics, programming and business sense and is common in analytics consultancies, banks and e-commerce firms. Experience with SQL and cloud platforms adds further value in interviews.

tidymodels Feature engineering Model evaluation Forecasting Model deployment
Solved for this roleStart 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.
3 questions free Unlock the rest in seconds
01

What is a pure function and why prefer them in data pipelines?

Save to ▾
Show answer
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.
02

How do you perform a t-test in R?

Save to ▾
Show answer
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
03

A customer table has multiple records per customer. How do you keep only the latest record for each?

Save to ▾
Show answer
I group by customer_id and keep the row with the latest updated_at using slice_max(updated_at, n = 1, with_ties = FALSE), then ungroup. An alternative is arrange(desc(updated_at)) followed by distinct(customer_id, .keep_all = TRUE). I check that updated_at is a proper date-time and has no NAs, since missing timestamps would be dropped or mis-sorted. Finally I confirm that n_distinct(customer_id) equals the number of rows.
04

Why do we split data into training and test sets, and what is cross-validation?

Save to ▾
Show answer
A model must be evaluated on data it has not seen, otherwise performance looks better than reality. We train on one part, typically 70 to 80 percent, and evaluate on the held-out test set. Cross-validation, such as 5-fold or 10-fold, splits training data into folds, trains on all but one and validates on the remaining fold in turn, giving a more stable estimate for tuning. In tidymodels, initial_split() and vfold_cv() handle this.
05

What is the multiple testing problem and how do you correct for it?

Save to ▾
Show answer
When you run many hypothesis tests, the chance of at least one false positive rises sharply. With 20 independent tests at alpha 0.05, it is about 64 percent. Corrections adjust p-values: Bonferroni multiplies by the number of tests and is conservative, Holm is a less strict step-down version, and Benjamini-Hochberg controls the false discovery rate. In R, p.adjust(pvals, method = 'BH') applies them, which is common when testing many metrics or segments.
06

Your function gives correct results when you test it but wrong results in the main script. What could be the cause?

Save to ▾
Show answer
A common cause is that the function reads a variable from the global environment instead of taking it as an argument. During testing that global variable had one value, and in the main script it has another. Lexical scoping finds it silently. I would check the function body for names not defined as arguments or locally, for example using codetools::findGlobals(fn), and pass everything explicitly so the function is self-contained.
07

How do you produce descriptive statistics for each group in R?

Save to ▾
Show answer
Combine summary functions with dplyr, or use quick helpers for exploration. summary(df$salary) quantile(df$salary, c(0.1, 0.5, 0.9), na.rm = TRUE) df %>% group_by(department) %>% summarise(n = n(), mean = mean(salary, na.rm = TRUE), median = median(salary, na.rm = TRUE), sd = sd(salary, na.rm = TRUE), iqr = IQR(salary, na.rm = TRUE)) skimr::skim(df)
08

How do you validate inputs inside an R function?

Save to ▾
Show answer
Fail early with clear messages using stopifnot(), stop() and match.arg(). summarise_kpi <- function(df, metric = c('revenue', 'orders', 'aov'), min_date = NULL) { stopifnot(is.data.frame(df), nrow(df) > 0) metric <- match.arg(metric) if (!is.null(min_date) && !inherits(min_date, 'Date')) { stop('min_date must be a Date', call. = FALSE) } required <- c('date', metric) missing <- setdiff(required, names(df)) if (length(missing)) stop('Missing columns: ', toString(missing)) # ... compute }
09

How do you reshape data between wide and long formats in R?

Save to ▾
Show answer
tidyr's pivot_longer() turns columns into rows and pivot_wider() does the reverse. library(tidyr) # wide: product, Jan, Feb, Mar long <- sales_wide %>% pivot_longer(cols = Jan:Mar, names_to = 'month', values_to = 'sales') wide <- long %>% pivot_wider(names_from = month, values_from = sales, values_fill = 0)
10

Write code using map2() and pmap() to iterate over multiple inputs.

Save to ▾
Show answer
map2() pairs two vectors and pmap() takes a list or data frame of arguments. library(purrr) prices <- c(100, 250, 400) qty <- c(2, 1, 5) map2_dbl(prices, qty, ~ .x * .y) # 200 250 2000 params <- tibble::tibble( region = c('North', 'South'), year = c(2025, 2026) ) pmap(params, function(region, year) { build_report(region = region, year = year) }) walk2(plots, paths, ~ ggsave(.y, .x))
11

A manager says a test with p = 0.06 proves the change had no effect. How do you respond?

Save to ▾
Show answer
I explain that failing to reject the null is not proof of no effect. A p-value of 0.06 means the evidence is weak or the test was underpowered, and the 0.05 cut-off is a convention, not a law. I would show the confidence interval for the effect, which probably ranges from slightly negative to clearly positive, check whether the sample size met the planned power and suggest extending the test or weighing the decision on cost and risk.
12

How do you check whether data is normally distributed in R?

Save to ▾
Show answer
Combine visual checks with formal tests, because tests become oversensitive with large samples. hist(x, breaks = 30) qqnorm(x); qqline(x, col = 'red') shapiro.test(x) # works for n between 3 and 5000 library(ggplot2) ggplot(df, aes(sample = x)) + stat_qq() + stat_qq_line() # for model residuals plot(lm_fit, which = 2)
13

Tell me about a time a model you built did not perform as expected after deployment.

Save to ▾
Show answer
Situation: a demand model I built performed well in testing but its errors doubled two months after launch. Task: diagnose and fix it. Action: I compared input distributions and found a new product category and a pricing change that the training data never saw. I added drift monitoring, retrained with recent data and set up monthly retraining. Result: accuracy returned to target, and I learned to plan monitoring before deployment, not after.
14

How do you calculate ROC AUC and plot an ROC curve in R?

Save to ▾
Show answer
yardstick in tidymodels or pROC compute AUC from predicted probabilities. library(yardstick) preds <- tibble(truth = factor(test$churned, levels = c('1', '0')), .pred_1 = test$prob) roc_auc(preds, truth, .pred_1) roc_curve(preds, truth, .pred_1) %>% autoplot() # with pROC library(pROC) r <- roc(test$churned, test$prob) auc(r); plot(r)
15

Your data is heavily skewed and the sample is small. Can you still use a t-test?

Save to ▾
Show answer
With small, heavily skewed samples the t-test's normality assumption is doubtful. I would check with a histogram, Q-Q plot or shapiro.test(). Options are a non-parametric test, wilcox.test() for two groups or kruskal.test() for more, a log transformation if the data is right-skewed and positive, or a bootstrap confidence interval for the difference in means. With large samples, the Central Limit Theorem usually makes the t-test acceptable.
16

Product wants to detect a lift in conversion from 5 to 5.5 percent. How many users do you need per group?

Save to ▾
Show answer
I use power analysis before the test starts. In R, power.prop.test(p1 = 0.05, p2 = 0.055, power = 0.8, sig.level = 0.05) gives roughly 31,000 users per group. Smaller lifts need far larger samples, since sample size scales with the inverse square of the effect. I would then convert the sample into test duration using daily traffic, round up to full weeks, and agree on the stopping rule in advance to avoid peeking bias.
17

Why should we hire you as a fresher for an R analyst role?

Save to ▾
Show answer
I have practical R skills, not just theory. In my projects I cleaned real datasets with dplyr, built ggplot2 dashboards and ran regression and hypothesis tests, and I can explain results simply. I also know SQL, which most analytics work needs. I learn quickly, accept feedback well and care about accuracy, so I double-check numbers before sharing them. I am ready to start contributing to reporting tasks from the first month.
18

You are building a fraud model where only 0.5 percent of transactions are fraud. How do you handle the imbalance?

Save to ▾
Show answer
Accuracy is useless here, since predicting no fraud gives 99.5 percent. I use stratified splits and evaluate with precision, recall, F1 and the precision-recall AUC. To help the model learn the minority class, I try class weights, downsampling the majority or SMOTE through the themis package in a recipe, applied only to training data. Then I tune the probability threshold based on the cost of missed fraud versus false alarms agreed with the business.
19

How do you build a logistic regression model for churn in R?

Save to ▾
Show answer
Use glm() with family = binomial; predictions with type = 'response' are probabilities. fit <- glm(churned ~ tenure + monthly_charges + contract, data = train, family = binomial) summary(fit) exp(coef(fit)) # odds ratios test$prob <- predict(fit, newdata = test, type = 'response') test$pred <- ifelse(test$prob > 0.5, 1, 0) table(actual = test$churned, predicted = test$pred)
20

Why is ungroup() important in dplyr?

Save to ▾
Show answer
A grouped data frame stays grouped after mutate() and some other verbs, so later operations silently run per group. For example, a mutate(share = sales / sum(sales)) meant to compute share of grand total would compute share within each group instead. Calling ungroup() after grouped work, or using .groups = 'drop' in summarise() or the .by argument for one-off grouping, prevents these subtle bugs in long pipelines.
21

How does a random forest work and which R packages implement it?

Save to ▾
Show answer
A random forest builds many decision trees, each on a bootstrap sample of rows and considering a random subset of features at each split, then averages their predictions for regression or takes a majority vote for classification. This reduces the variance of single trees and handles non-linear relationships well. In R, randomForest is the classic package and ranger is a much faster implementation. Key parameters are the number of trees, mtry and minimum node size.
22

What is the difference between Pearson and Spearman correlation?

Save to ▾
Show answer
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.
23

Explain the d, p, q and r functions for probability distributions in R.

Save to ▾
Show answer
Each distribution has four functions: d for density, p for cumulative probability, q for quantiles and r for random draws. dnorm(0) # density at 0 pnorm(1.96) # P(Z <= 1.96) = 0.975 qnorm(0.975) # 1.96 rnorm(5, mean = 50, sd = 10) dbinom(3, size = 10, prob = 0.2) # exactly 3 successes ppois(2, lambda = 4) # P(X <= 2) qt(0.975, df = 20) # t critical value
24

How do you handle errors in R code?

Save to ▾
Show answer
tryCatch() catches errors and warnings so a script can recover or log them; finally runs cleanup. read_safe <- function(path) { tryCatch({ readr::read_csv(path, show_col_types = FALSE) }, warning = function(w) { message('Warning in ', path, ': ', conditionMessage(w)) NULL }, error = function(e) { message('Failed: ', path, ' - ', conditionMessage(e)) NULL }, finally = message('Done: ', path)) }
25

Write dplyr code to find total and average sales by city, sorted by total.

Save to ▾
Show answer
Group, summarise and sort: library(dplyr) city_summary <- sales %>% filter(!is.na(amount)) %>% group_by(city) %>% summarise( orders = n(), total = sum(amount), avg_order = mean(amount), .groups = 'drop' ) %>% arrange(desc(total)) head(city_summary, 10)
26

What is the purrr map family?

Save to ▾
Show answer
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.
27

What are semi_join() and anti_join() used for?

Save to ▾
Show answer
They are filtering joins: they keep rows of the left table based on matches in the right table but add no columns. semi_join() keeps rows that have a match, and anti_join() keeps rows that have no match. For example, anti_join(customers, orders, by = 'customer_id') lists customers who never ordered. They are also safer than inner joins for filtering, since they never duplicate rows when the right table has repeated keys.
28

How do you apply the same transformation to many columns in dplyr?

Save to ▾
Show answer
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}'))
29

What is the difference between reactive(), observe() and observeEvent() in Shiny?

Save to ▾
Show answer
reactive() creates a cached value that other code can read, such as filtered data, and it is lazy, recomputing only when needed. observe() runs code for its side effects whenever any reactive dependency changes, returning nothing. observeEvent() runs side effects only when a specific event fires, such as a button click, ignoring other dependencies. Use reactive() for computing values and observeEvent() for actions like saving data or showing notifications.
30

What is tidymodels and how does it compare with caret?

Save to ▾
Show answer
tidymodels is a collection of packages for modelling with tidyverse principles: rsample for splitting and resampling, recipes for preprocessing, parsnip for a unified model interface, workflows to bundle them, tune for hyperparameter tuning and yardstick for metrics. caret, by the same original author, is an older single package that does similar work with one train() function. caret is stable and still widely used, but new development happens in tidymodels.
31

How do you test whether two categorical variables are related in R?

Save to ▾
Show answer
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)
32

Explain Type I and Type II errors.

Save to ▾
Show answer
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.
33

Your model has R-squared 0.92 on training data but 0.55 on test data. What do you do?

Save to ▾
Show answer
The gap indicates overfitting or data leakage. I first check for leakage, such as a feature computed using future information or the target itself, or duplicate records across train and test. Then I simplify the model, add regularization, reduce features or tune hyperparameters with cross-validation instead of a single split. If data is time-based, I make sure the split is chronological. I compare against a simple baseline to judge real improvement.
34

Tell me about feedback you received in a code review and what you changed.

Save to ▾
Show answer
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.
35

Some stakeholders are colour-blind. How do you design charts for them?

Save to ▾
Show answer
I use colour-blind-safe palettes such as viridis with scale_colour_viridis_d() or the Okabe-Ito palette, and avoid red-green contrasts. I never rely on colour alone: I add direct labels, different shapes or line types, and facets. I limit categories to around six colours and highlight one key series while greying the rest. I also check charts with a colour-blindness simulator, such as the colorblindr package, before sharing.
36

What is the difference between errors, warnings and messages in R?

Save to ▾
Show answer
An error, raised with stop(), halts execution because something cannot continue. A warning, raised with warning(), lets code continue but signals a possible problem, such as NAs introduced by coercion. A message, from message(), is informational, such as progress updates. Messages go to stderr, so they can be suppressed with suppressMessages() without hiding results. Use print() or cat() for output the user requested, not for diagnostics.
37

How would you compare R and Python for a data role?

Save to ▾
Show answer
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.
38

What window functions does dplyr provide?

Save to ▾
Show answer
Window functions return one value per row while looking at other rows in the group. Common ones are lag() and lead() for previous or next values, row_number(), min_rank() and dense_rank() for ranking, cumsum() and cummean() for running totals, and ntile() for buckets. For example, group_by(product) %>% arrange(month) %>% mutate(prev = lag(sales)) gives the previous month's sales per product, which is the basis for growth calculations.
39

How do you do feature engineering with recipes in tidymodels?

Save to ▾
Show answer
A recipe defines preprocessing steps that are learned on training data and applied identically to new data. rec <- recipe(price ~ ., data = train) %>% update_role(listing_id, new_role = 'id') %>% step_date(listed_on, features = c('month', 'dow')) %>% step_rm(listed_on) %>% step_log(area_sqft) %>% step_other(locality, threshold = 0.01) %>% step_dummy(all_nominal_predictors()) %>% step_normalize(all_numeric_predictors()) prep(rec) %>% bake(new_data = NULL) %>% glimpse()
40

Walk me through an end-to-end machine learning project you have done in R.

Save to ▾
Show answer
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.

Frequently asked questions

What does a Data Scientist (R) do?

A Data Scientist using R builds predictive models for churn, risk, demand and pricing, from feature engineering to evaluation and deployment. They use tidymodels, glmnet, ranger and forecasting packages, explain models to business teams and monitor them after launch. The role combines statistics, programming and business sense and is common in analytics consultancies, banks and e-commerce firms. Experience with SQL and cloud platforms adds further value in interviews.

Which skills are tested in a Data Scientist (R) interview?

Expect questions on tidymodels, Feature engineering, Model evaluation, Forecasting, Model deployment. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Data Scientist (R) interview?

Revise Modelling and Machine Learning in R, Statistics and Hypothesis Testing, Data Wrangling with dplyr and tidyr, Functions and Functional Programming first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.