Skip to content

R Programming Interview Questions for Freshers

40 questions with answers for candidates with Freshers — 26 easy, 14 medium.

What interviewers expect: freshers

Freshers face questions on R basics, data types, subsetting, dplyr verbs, simple ggplot2 charts and core statistics such as mean, median, standard deviation and p-values. Many interviews include a short live coding task to clean and summarise a dataset, plus SQL questions. Interviewers value clear explanations of academic or personal projects and a willingness to learn.

This set is weighted towards R Basics and Data Types (9), Statistics and Hypothesis Testing (8), Data Wrangling with dplyr and tidyr (6), Reports, Shiny and Production R (4).

R fundamentals and data types dplyr and ggplot2 basics Descriptive statistics Project explanation
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.
3 questions free Unlock the rest in seconds
01

What is R Markdown and why is it useful?

Save to ▾
Show answer
R Markdown is a file format that combines narrative text written in Markdown with R code chunks. When rendered with knitr, the code runs and its output, such as tables and charts, is inserted into an HTML, PDF or Word document. This makes reports reproducible: when data changes, you re-render instead of copying charts manually. It is used for monthly reports, research papers, client deliverables and teaching material.
02

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.
03

Bars in your chart appear in alphabetical order instead of by value. How do you fix it?

Save to ▾
Show answer
ggplot2 orders discrete axes by factor levels, which default to alphabetical. I reorder the factor by the value with forcats: aes(x = fct_reorder(city, sales), y = sales), and add coord_flip() or put the category on the y-axis for long labels. For a fixed custom order, such as months or ratings, I set levels explicitly with factor(x, levels = c(...)). fct_infreq() orders by frequency for count bars.
04

What is the Central Limit Theorem and why is it important?

Save to ▾
Show answer
The Central Limit Theorem says that the distribution of sample means approaches a normal distribution as sample size grows, roughly beyond 30, regardless of the population's shape, provided observations are independent with finite variance. It is why t-tests, confidence intervals and A/B test calculations work on non-normal data such as order values. You can demonstrate it in R by repeatedly sampling from rexp() and plotting a histogram of the means.
05

Explain the apply family of functions in R.

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

What is plumber in R?

Save to ▾
Show answer
plumber turns R functions into REST API endpoints using special comments. You annotate a function with #* @get /predict and its arguments become query parameters, then run the API with pr_run(). Other systems, such as a Java web app or a Python service, can call the R model over HTTP and receive JSON. It is commonly used to serve model predictions, and it can be deployed in Docker or on Posit Connect.
07

What is a factor in R and when would you use one?

Save to ▾
Show answer
A factor stores categorical data as integer codes with a set of labels called levels. Factors are used for variables like gender, city or rating, and modelling functions such as lm() turn them into dummy variables automatically. Ordered factors, created with factor(x, levels = c('Low', 'Medium', 'High'), ordered = TRUE), support comparisons. A common pitfall is as.numeric() on a numeric factor, which returns codes; use as.numeric(as.character(f)) instead.
08

What is a p-value?

Save to ▾
Show answer
A p-value is the probability of seeing results at least as extreme as the observed ones if the null hypothesis were true. A small p-value, typically below 0.05, means the data would be unusual under the null, so we reject it. It is not the probability that the null hypothesis is true and does not measure effect size. A tiny, unimportant difference can be significant with a huge sample, so always report effect sizes and confidence intervals too.
09

Finance says 120 transactions are missing from your report compared with their system. How do you find them?

Save to ▾
Show answer
I load both datasets and standardise the key, for example trimming spaces and matching data types for transaction_id. Then anti_join(finance, report, by = 'transaction_id') lists transactions in finance but not in my report, and the reverse anti_join shows extras. I examine the missing rows for patterns such as a date range, status or filter in my code. Usually the cause is a timezone cut-off or an excluded status.
10

Your analysis gives slightly different results every time you run it. How do you make it reproducible?

Save to ▾
Show answer
Functions like sample(), rnorm() and random train-test splits depend on the random number generator. I call set.seed(42) at the start of the script so the same random sequence is generated every run, which lets reviewers reproduce results. For parallel code I use reproducible streams, for example future with seed = TRUE. I also record the R version, because the default sampling algorithm changed in R 3.6.0 and can change results between versions.
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 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
13

Your manager says your charts are confusing. How do you respond?

Save to ▾
Show answer
I would thank them and ask which part was unclear, such as too many colours, missing labels or an unclear message. In my internship this happened with a crowded chart of twelve product lines. I simplified it by highlighting the top three, greying the rest, adding a clear title stating the finding and labelling values directly. My manager found the new version easy to present, and I now review every chart for one clear message.
14

Describe a time you learned something from a teammate.

Save to ▾
Show answer
Situation: during my final-year project, our group's R code ran very slowly on a large dataset. Task: I was responsible for the cleaning step. Action: a teammate showed me how to replace my nested for loops with vectorized dplyr operations and explained why loops were slow. I practised the approach on other parts of the code. Result: processing time fell from twenty minutes to under one, and I shared the lesson with the rest of the group.
15

How do you keep improving your statistics knowledge?

Save to ▾
Show answer
I revise core concepts from a standard textbook and practise each method in R on public datasets, so I understand both the theory and the code. For example, after learning hypothesis testing, I reproduced published A/B test results from Kaggle datasets. I follow the R Weekly newsletter and read package vignettes. When I meet a method at work that I do not understand, I note it and study it that weekend.
16

What is the difference between variance and standard deviation?

Save to ▾
Show answer
Variance is the average squared deviation from the mean, and standard deviation is its square root. Because variance is in squared units, standard deviation is easier to interpret since it uses the same units as the data. In R, var() and sd() both use the sample formula with n - 1 in the denominator. For example, delivery times with mean 30 minutes and SD 5 minutes are far more consistent than with SD 15.
17

What is the difference between base R graphics and ggplot2?

Save to ▾
Show answer
Base graphics use functions like plot(), hist() and barplot() that draw directly on a device, and you add elements with lines() or legend() step by step. They are quick for exploration. ggplot2 builds plots as objects from layers using the grammar of graphics, handles legends and facets automatically and is easier to style consistently. Base plots are fine for quick checks, while ggplot2 is preferred for reports and publications.
18

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'))
19

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

What is a tibble and how does it differ from a base data frame?

Save to ▾
Show answer
A tibble is the tidyverse version of a data frame. It prints only the rows and columns that fit the screen along with column types, never converts strings to factors, never changes column names, does not partially match with $ and always returns a tibble when subsetting with [ ]. It also supports list-columns easily. You convert with as_tibble(). Tibbles prevent many silent bugs, though some older packages expect base data frames.
21

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
22

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

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

The finance team wants the daily output as a formatted Excel file, not a CSV. How do you produce it?

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

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.
26

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
27

What are the assumptions of linear regression?

Save to ▾
Show answer
The main assumptions are a linear relationship between predictors and the outcome, independent errors, constant variance of errors (homoscedasticity), normally distributed errors for valid inference and no severe multicollinearity. In R, plot(fit) shows residuals versus fitted values, a Q-Q plot and leverage, and car::vif() checks collinearity. Violations can be addressed with transformations like log, robust standard errors or different models such as GLMs.
28

What is the difference between if, ifelse() and dplyr's if_else()?

Save to ▾
Show answer
if is a control-flow statement that checks a single TRUE or FALSE value and runs one branch, used for program logic. ifelse() is vectorized and returns a vector of the same length as the condition, used for transforming data. dplyr::if_else() is a stricter vectorized version that requires both outputs to have the same type, preserves classes like dates and has a missing argument for NA conditions, making it safer than ifelse().
29

What are the atomic data types in R?

Save to ▾
Show answer
R has six atomic types: logical (TRUE/FALSE), integer (5L), double or numeric (3.14), character ('text'), complex (2+3i) and raw (bytes). typeof() returns the internal type while class() returns the class attribute used for method dispatch. For example, typeof(5) is 'double' but typeof(5L) is 'integer'. Knowing types matters because mixing them in one vector triggers coercion to the most flexible type.
30

What are the principles of tidy data?

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

Explain the confusion matrix and the metrics derived from it.

Save to ▾
Show answer
A confusion matrix compares actual and predicted classes: true positives, false positives, true negatives and false negatives. Accuracy is the share of correct predictions. Precision is TP / (TP + FP), how many predicted positives are correct. Recall is TP / (TP + FN), how many actual positives were found. F1 is their harmonic mean. For a loan default model, recall matters if missing defaulters is costly; precision matters if rejecting good customers is costly.
32

What is the difference between <- and = for assignment in R?

Save to ▾
Show answer
Both assign values at the top level, but <- is the conventional assignment operator in R style guides, while = is mainly used to pass named arguments inside function calls. For example, mean(x = 1:10) passes an argument and does not create x in the workspace, but mean(x <- 1:10) creates x as a side effect. Using <- for assignment keeps code readable and avoids confusion between assignment and argument matching.
33

A numeric column in your data has been read as character. How do you fix it?

Save to ▾
Show answer
I first find the offending values, for example with unique(df$amount[is.na(as.numeric(df$amount))]), which reveals entries like '1,200', 'NA ' or '-'. Then I clean them, removing commas with gsub(',', '', x) and spaces with trimws(), and convert with as.numeric(). With readr I can also pass na = c('', '-', 'NA') and col_types so the column is parsed correctly at load time instead of being fixed later.
34

What are facets in ggplot2?

Save to ▾
Show answer
Facets split a plot into small multiples, one panel per category, sharing the same axes and geoms. facet_wrap(~ region) wraps panels for one variable, and facet_grid(rows = vars(segment), cols = vars(year)) creates a grid for two variables. scales = 'free_y' lets each panel have its own y-axis. Facets are often clearer than one chart with many overlapping coloured lines, for example comparing sales trends across ten states.
35

Why does correlation not imply causation?

Save to ▾
Show answer
Two variables can move together because of a third confounding variable, reverse causation or pure chance. For example, ice cream sales and drowning incidents are correlated because both rise in summer. To claim causation you need a randomized experiment such as an A/B test, or careful causal methods like difference-in-differences or regression with controls. In interviews, mention that observational correlations are useful for hypotheses but not proof of impact.
36

What are the main dplyr verbs?

Save to ▾
Show answer
dplyr has a small set of verbs for data transformation: filter() keeps rows that meet conditions, select() picks columns, mutate() creates or changes columns, arrange() sorts rows, summarise() reduces groups to summary rows and group_by() defines groups for the next operations. Others include distinct(), rename(), relocate(), count() and slice(). Each takes a data frame as the first argument and returns a data frame, so verbs chain naturally with the pipe.
37

What does a 95 percent confidence interval mean?

Save to ▾
Show answer
If we repeated the sampling many times and built an interval each time, about 95 percent of those intervals would contain the true population value. It does not mean there is a 95 percent probability that this specific interval contains it. A narrow interval shows precise estimation and a wide one shows uncertainty. For example, average order value of 850 INR with CI 820 to 880 is far more useful than CI 600 to 1100.
38

What is type coercion in R and how can it cause bugs?

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

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 = '-')
40

Why did you choose to learn R?

Save to ▾
Show answer
I chose R because I enjoy working with data and statistics, and R is designed exactly for that. During my coursework I used it for a project analysing student performance, where dplyr and ggplot2 helped me move from raw data to clear insights quickly. I like that results are reproducible with R Markdown. I am also learning SQL and basic Python, so I can work comfortably in a mixed team and pick the right tool for each task.

Frequently asked questions

What is asked in R Programming interviews for Freshers?

Freshers face questions on R basics, data types, subsetting, dplyr verbs, simple ggplot2 charts and core statistics such as mean, median, standard deviation and p-values. Many interviews include a short live coding task to clean and summarise a dataset, plus SQL questions. Interviewers value clear explanations of academic or personal projects and a willingness to learn.

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 Freshers?

Focus first on R fundamentals and data types, dplyr and ggplot2 basics, Descriptive statistics, Project explanation.