Skip to content

Practical R Programming Interview Questions

45 questions with answers. Hands-on questions where you write code, a query, a formula or concrete steps.

How to approach these questions

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.

Solved — practicalStart 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

How do you install and load a package, and what is the difference between library() and require()?

Save to ▾
Show answer
install.packages() downloads from CRAN once; library() loads it in every session. library() throws an error if the package is missing, while require() returns FALSE with a warning, so require() suits conditional checks. install.packages('dplyr') library(dplyr) if (!require('data.table')) { install.packages('data.table') library(data.table) }
02

How do you create sequences and repeated values in R?

Save to ▾
Show answer
seq(), rep() and the colon operator build most vectors. 1:10 # integers 1 to 10 seq(0, 100, by = 10) # 0, 10, ..., 100 seq(1, 2, length.out = 5) # 5 evenly spaced values rep(c('A', 'B'), times = 3) # A B A B A B rep(c('A', 'B'), each = 2) # A A B B seq_along(c('x', 'y', 'z')) # 1 2 3, safe for empty vectors seq_len(0) # empty, unlike 1:0
03

How do you handle missing values in calculations in R?

Save to ▾
Show answer
Most summary functions return NA if any value is missing, so pass na.rm = TRUE or remove NAs first. x <- c(10, NA, 30, 40) mean(x) # NA mean(x, na.rm = TRUE) # 26.67 sum(is.na(x)) # count missing: 1 x[!is.na(x)] # drop NAs x[is.na(x)] <- median(x, na.rm = TRUE) # impute df[complete.cases(df), ] # rows with no NA
04

How do you find out why your R code is slow?

Save to ▾
Show answer
Measure before optimizing. system.time() gives total time, bench::mark() compares alternatives, and profvis shows which lines consume time and memory. system.time(result <- slow_function(df)) bench::mark( loop = sum_loop(x), vec = sum(x) ) library(profvis) profvis({ out <- clean_data(raw) model <- fit_model(out) })
05

How do you manage working directories and file paths in an R project?

Save to ▾
Show answer
getwd() shows and setwd() changes the working directory, but a hardcoded setwd() breaks on other machines. RStudio projects with the here package build paths relative to the project root. getwd() library(here) sales <- read.csv(here('data', 'sales.csv')) write.csv(summary_df, here('output', 'summary.csv'), row.names = FALSE) file.exists(here('data', 'sales.csv')) list.files(here('data'), pattern = 'csv$')
06

Show different ways to index vectors and data frames in R.

Save to ▾
Show answer
R indexes from 1 and supports positive, negative, logical and name-based indexing. x <- c(a = 10, b = 20, c = 30, d = 40) x[2] # 20 x[-1] # drop first x[c('a', 'd')] # by name x[x > 15] # logical filter which(x > 15) # positions df[df$age > 30, c('name', 'city')] df[order(-df$salary), ][1:5, ] # top 5 salaries
07

How do you create, modify and combine lists in R?

Save to ▾
Show answer
Lists are built with list(), modified by name and combined or flattened when needed. emp <- list(name = 'Asha', skills = c('R', 'SQL'), exp = 3) emp$city <- 'Pune' # add element emp[['exp']] <- 4 # update emp$skills <- NULL # remove names(emp) parts <- lapply(1:3, function(i) data.frame(id = i, sq = i^2)) do.call(rbind, parts) # combine data frames unlist(list(a = 1, b = list(c = 2))) # flatten
08

Write common data.table operations for filtering, aggregating and joining.

Save to ▾
Show answer
Read, filter, aggregate, add columns by reference and join: library(data.table) DT <- fread('orders.csv') DT[status == 'delivered', .N, by = city] DT[, revenue := qty * price] DT[, .(total = sum(revenue)), by = .(city, month)][order(-total)] customers <- fread('customers.csv') merged <- customers[DT, on = 'customer_id'] fwrite(merged, 'merged.csv')
09

How do you clean and manipulate text data in R?

Save to ▾
Show answer
The stringr package gives consistent functions starting with str_. library(stringr) x <- c(' Rahul Sharma ', 'priya VERMA') str_trim(x) str_to_title(x) str_detect(x, 'Sharma') str_replace_all('9876-543-210', '-', '') str_extract('Order ID: 45821', '[0-9]+') str_split('a,b,c', ',')[[1]] str_pad('7', width = 3, pad = '0') # '007'
10

Write code to fit one regression model per group using nested data.

Save to ▾
Show answer
Fit one model per region with list-columns: library(dplyr); library(tidyr) library(purrr); library(broom) models <- sales %>% group_by(region) %>% nest() %>% mutate( fit = map(data, ~ lm(revenue ~ ad_spend, data = .x)), coefs = map(fit, tidy), r2 = map_dbl(fit, ~ glance(.x)$r.squared) ) models %>% unnest(coefs) %>% select(region, term, estimate)
11

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)
12

How do you create a column with multiple conditions in dplyr?

Save to ▾
Show answer
case_when() evaluates conditions in order and returns the value of the first one that is TRUE; .default handles the rest. customers <- customers %>% mutate(segment = case_when( spend >= 50000 ~ 'Platinum', spend >= 20000 ~ 'Gold', spend >= 5000 & visits > 5 ~ 'Silver', .default = 'Regular' )) # simple two-way split mutate(df, high_value = if_else(spend > 20000, 'Yes', 'No'))
13

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)
14

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}'))
15

Write a reusable function that summarises any numeric column by any grouping column using dplyr.

Save to ▾
Show answer
Use {{ }} to pass columns into data-masking verbs: library(dplyr) summarise_by <- function(data, group_col, value_col) { data %>% group_by({{ group_col }}) %>% summarise( n = n(), mean_val = mean({{ value_col }}, na.rm = TRUE), total = sum({{ value_col }}, na.rm = TRUE), .groups = 'drop' ) %>% arrange(desc(total)) } summarise_by(sales, city, amount)
16

How do you split one column into several, or combine columns into one?

Save to ▾
Show answer
tidyr provides separate_wider_delim() to split and unite() to combine. library(tidyr) df <- tibble(full_name = c('Amit Kumar', 'Neha Singh'), dob = c('12-05-1999', '03-11-2000')) df %>% separate_wider_delim(full_name, delim = ' ', names = c('first', 'last')) df %>% separate_wider_delim(dob, '-', names = c('d', 'm', 'y')) %>% unite('dob_iso', y, m, d, sep = '-')
17

Write ggplot2 code for a monthly sales line chart with points.

Save to ▾
Show answer
A basic time-series line chart: library(ggplot2) ggplot(monthly, aes(x = month, y = sales)) + geom_line(colour = 'steelblue', linewidth = 1) + geom_point(size = 2) + scale_y_continuous(labels = scales::label_comma()) + scale_x_date(date_labels = '%b %Y', date_breaks = '2 months') + labs(title = 'Monthly Sales', x = NULL, y = 'Sales (INR)') + theme_minimal()
18

How do you customise scales, labels and themes in ggplot2?

Save to ▾
Show answer
Scales control how data maps to visuals, and themes control non-data elements. p + scale_y_continuous(labels = scales::label_percent()) + scale_fill_brewer(palette = 'Set2') + labs(title = 'Conversion by Channel', subtitle = 'FY 2025-26', caption = 'Source: CRM') + theme_minimal(base_size = 12) + theme(legend.position = 'bottom', plot.title = element_text(face = 'bold'), panel.grid.minor = element_blank())
19

Write code to show the distribution of order values using a histogram and a boxplot by category.

Save to ▾
Show answer
Histogram for one variable, boxplot to compare groups: ggplot(orders, aes(x = order_value)) + geom_histogram(binwidth = 500, fill = 'grey60', colour = 'white') + labs(x = 'Order value (INR)', y = 'Orders') ggplot(orders, aes(x = category, y = order_value)) + geom_boxplot(outlier.alpha = 0.3) + coord_flip() + labs(x = NULL, y = 'Order value (INR)')
20

How do you save a ggplot chart for a report or presentation?

Save to ▾
Show answer
ggsave() saves the last plot or a named plot with exact size and resolution. p <- ggplot(df, aes(city, sales)) + geom_col() ggsave('output/sales_by_city.png', plot = p, width = 8, height = 5, dpi = 300) ggsave('output/sales_by_city.pdf', plot = p, width = 8, height = 5) # vector, sharp at any zoom # svg for web use ggsave('output/sales_by_city.svg', plot = p)
21

How do you add labels and annotations to a ggplot chart?

Save to ▾
Show answer
Use geom_text() or geom_label() for data labels and annotate() for one-off notes. ggplot(city_sales, aes(reorder(city, sales), sales)) + geom_col(fill = 'steelblue') + geom_text(aes(label = scales::comma(sales)), hjust = -0.1, size = 3.5) + annotate('text', x = 2, y = 9e5, label = 'Festive season push') + coord_flip() + expand_limits(y = 1.1e6) + labs(x = NULL, y = 'Sales (INR)')
22

How would you create a reusable branded theme for all team charts?

Save to ▾
Show answer
Wrap theme settings and palettes in functions stored in an internal package: theme_team <- function(base_size = 12) { theme_minimal(base_size = base_size) + theme( plot.title = element_text(face = 'bold', colour = '#1F3A5F'), panel.grid.minor = element_blank(), legend.position = 'top' ) } scale_fill_team <- function(...) { scale_fill_manual(values = c('#1F3A5F', '#F28C28', '#2A9D8F'), ...) } ggplot(df, aes(x, y, fill = g)) + geom_col() + theme_team() + scale_fill_team()
23

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
24

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)
25

How do you compare means across more than two groups in R?

Save to ▾
Show answer
Use one-way ANOVA, then a post-hoc test to see which pairs differ. fit <- aov(sales ~ region, data = stores) summary(fit) # overall F-test TukeyHSD(fit) # pairwise comparisons # check assumptions plot(fit, which = 2) # Q-Q of residuals bartlett.test(sales ~ region, data = stores) # non-parametric alternative kruskal.test(sales ~ region, data = stores)
26

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)
27

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
28

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)
29

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)) }
30

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))
31

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 }
32

How do you debug an R function?

Save to ▾
Show answer
After an error, traceback() shows the call stack so I can see which function failed. I insert browser() inside a function to pause execution and inspect variables interactively, stepping with n and continuing with c. debug(fn) or debugonce(fn) enters the browser on the next call without editing code. options(error = recover) lets me choose a frame to inspect after an error. RStudio breakpoints offer the same features visually.
33

Write a recursive function in R to calculate factorial and Fibonacci numbers.

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

How do you use Reduce(), Filter() and Map() in base R?

Save to ▾
Show answer
These higher-order functions come from functional programming. nums <- 1:10 Filter(function(x) x %% 2 == 0, nums) # even numbers Map(function(a, b) a + b, 1:3, 4:6) # list: 5 7 9 Reduce(`+`, 1:5, accumulate = TRUE) # 1 3 6 10 15 # join many data frames on a common key dfs <- list(sales, targets, regions) Reduce(function(x, y) merge(x, y, by = 'region_id'), dfs) # purrr equivalents: keep(), map2(), reduce()
35

How do you build a linear regression model in R?

Save to ▾
Show answer
lm() fits linear models using formula syntax; summary() shows coefficients and fit. fit <- lm(sales ~ ad_spend + price + region, data = stores) summary(fit) coef(fit) confint(fit) # 95% CIs for coefficients predict(fit, newdata = new_stores, interval = 'prediction') par(mfrow = c(2, 2)); plot(fit) # diagnostic plots broom::tidy(fit) # coefficients as a tibble
36

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)
37

Write a tidymodels workflow to train and evaluate a random forest.

Save to ▾
Show answer
Split, preprocess, specify, fit and evaluate: library(tidymodels) set.seed(42) split <- initial_split(df, prop = 0.8, strata = churned) train <- training(split); test <- testing(split) rec <- recipe(churned ~ ., data = train) %>% step_impute_median(all_numeric_predictors()) %>% step_dummy(all_nominal_predictors()) rf <- rand_forest(trees = 500) %>% set_engine('ranger') %>% set_mode('classification') wf_fit <- workflow() %>% add_recipe(rec) %>% add_model(rf) %>% last_fit(split) collect_metrics(wf_fit)
38

How do you perform k-means clustering in R?

Save to ▾
Show answer
Scale features first, choose k using the elbow or silhouette method, then fit. library(factoextra) X <- scale(customers[, c('recency', 'frequency', 'monetary')]) fviz_nbclust(X, kmeans, method = 'wss') # elbow fviz_nbclust(X, kmeans, method = 'silhouette') set.seed(42) km <- kmeans(X, centers = 4, nstart = 25) customers$segment <- km$cluster aggregate(cbind(recency, frequency, monetary) ~ segment, data = customers, FUN = mean)
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

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)
41

Write a minimal Shiny app that filters sales by region and plots them.

Save to ▾
Show answer
A ui with an input and an output, and a server that reacts to the input: library(shiny); library(ggplot2); library(dplyr) ui <- fluidPage( selectInput('region', 'Region', choices = unique(sales$region)), plotOutput('trend') ) server <- function(input, output, session) { filtered <- reactive(filter(sales, region == input$region)) output$trend <- renderPlot({ ggplot(filtered(), aes(month, revenue)) + geom_line() }) } shinyApp(ui, server)
42

How do you generate the same report for each of 20 regions automatically?

Save to ▾
Show answer
Use a parameterized Quarto or R Markdown report and render it in a loop. # report.qmd header: # params: # region: 'North' # then use params$region in the code regions <- unique(sales$region) purrr::walk(regions, function(r) { quarto::quarto_render( 'report.qmd', execute_params = list(region = r), output_file = paste0('report_', r, '.html') ) })
43

How do you write unit tests for an R function?

Save to ▾
Show answer
testthat organises tests into files under tests/testthat/ using expectations. # tests/testthat/test-gst.R test_that('gst_price adds 18 percent by default', { expect_equal(gst_price(100), 118) expect_equal(gst_price(c(100, 200)), c(118, 236)) }) test_that('gst_price rejects text input', { expect_error(gst_price('abc'), 'numeric') }) # run all tests devtools::test()
44

How do you connect R to a SQL database and run queries?

Save to ▾
Show answer
DBI provides a common interface, with drivers such as RPostgres, RMariaDB or odbc. library(DBI) con <- dbConnect(RPostgres::Postgres(), host = Sys.getenv('DB_HOST'), dbname = 'sales', user = Sys.getenv('DB_USER'), password = Sys.getenv('DB_PASS')) orders <- dbGetQuery(con, 'SELECT * FROM orders WHERE order_date >= $1', params = list('2026-01-01')) dbWriteTable(con, 'daily_summary', summary_df, append = TRUE) dbDisconnect(con)
45

How do you add logging to a production R script?

Save to ▾
Show answer
The logger package gives levelled, timestamped logs written to the console or a file. library(logger) log_appender(appender_file('logs/etl.log')) log_threshold(INFO) log_info('ETL started') res <- tryCatch({ df <- load_orders() log_info('Loaded {nrow(df)} rows') df }, error = function(e) { log_error('Load failed: {conditionMessage(e)}') quit(status = 1) }) log_info('ETL finished')

Frequently asked questions

Why are practical questions important?

Most technical rounds include at least one live task. Practising the exact typing and reasoning makes you calm and fast in the real round.

How should I answer them?

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.