R - Interview Questions
Modern R Interview Questions
Section titled “Modern R Interview Questions”This list of R interview questions has been updated to reflect modern data science practices. Questions cover core R concepts as well as the tidyverse ecosystem, which is central to many contemporary R workflows. Good interviewers will explore your understanding of concepts rather than just memorization.
Q: What is R, and what are its main strengths for data analysis?
R is a programming language and environment designed for statistical computing and graphics. Its main strengths are:
- Vast Package Ecosystem: CRAN (the Comprehensive R Archive Network) hosts thousands of packages for nearly any statistical or data-centric task.
- The Tidyverse: A powerful, cohesive collection of packages (like
dplyr,ggplot2,readr) designed for data science that share a common design philosophy, making data manipulation, exploration, and visualization intuitive and efficient. - Statistical Power: It was built by statisticians, for statisticians. It offers unparalleled support for both classic and cutting-edge statistical modeling.
- Reproducibility: Tools like R Markdown and
renvmake it easy to create reproducible analyses and reports.
Q: What is the tidyverse and why is it so popular?
The tidyverse is an opinionated collection of R packages for data science, all sharing an underlying design philosophy, grammar, and data structures. It’s popular because it provides a consistent and highly effective workflow for the most common data science tasks: importing (readr), tidying (tidyr), manipulating (dplyr), visualizing (ggplot2), and functional programming (purrr). Its use of pipes (%>% or |>) makes code highly readable by chaining operations together logically.
Q: What’s the difference between a data.frame and a tibble?
A tibble is the tidyverse’s modern take on the base R data.frame. Key differences include:
- Printing: Tibbles print only the first 10 rows and columns that fit on screen, preventing accidental console flooding. They also show column types.
- Subsetting:
[on a tibble always returns another tibble. For adata.frame, it might return a vector, which can cause bugs. - No Automatic Conversions: Tibbles do not convert strings to factors or change column names, making them more predictable and stable in scripts.
Q: What are the main verbs of dplyr? Provide a simple example of a data pipeline.
The main verbs are:
select(): picks columns by name.filter(): picks rows by a logical condition.arrange(): reorders rows.mutate(): creates new columns or transforms existing ones.summarise()(orsummarize()): collapses many values down to a single summary.group_by(): performs operations on groups of data.
Example pipeline: Find the average mass of droids in the starwars dataset.
library(dplyr)starwars %>% filter(species == "Droid") %>% summarise(avg_mass = mean(mass, na.rm = TRUE))Q: Explain the difference between [ and [[ for subsetting.
This is a fundamental concept.
[[extracts a single element. The result will have the type of that element. For a list,my_list[[1]]returns the first object inside the list.[extracts a collection of elements. The result will have the same type as the original object. For a list,my_list[1]returns a new list containing only the first element of the original list.
Analogy: Think of a train. train[[1]] gets you the contents of the first car. train[1] gets you a new, one-car train.
Q: How do you handle missing values (NA) in R?
- Identification: Use
is.na()to create a logical vector indicating whereNAs are. - Removal: Use
na.omit()ortidyr::drop_na()to remove rows with anyNAs. - Calculation: Many functions like
mean(),sum(), andsd()have anna.rm = TRUEargument to ignoreNAs during calculation. - Imputation: Use
tidyr::replace_na()to replaceNAs with a specific value (e.g., the mean or median of the column).
Q: What is vector recycling? Give an example.
When performing an operation on two vectors of different lengths, R automatically repeats (recycles) the elements of the shorter vector to match the length of the longer one. A warning is issued if the longer vector’s length is not a multiple of the shorter one.
Example:
c(1, 2, 3, 4, 5, 6) + c(10, 20)# The shorter vector is recycled to become c(10, 20, 10, 20, 10, 20)# Result: [1] 11 22 13 24 15 26Q: How would you make an R project reproducible?
- Project Organization: Use RStudio Projects to keep all files (code, data, reports) self-contained in a single directory.
- Dependency Management: Use the
renvpackage.renv::init()creates a project-specific library, andrenv::snapshot()saves the exact versions of all packages used, ensuring others can recreate the environment perfectly withrenv::restore(). - Analysis as a Report: Use R Markdown (
.Rmd) to weave code, output (plots, tables), and narrative text together. This creates a dynamic document that can be re-run to produce the full analysis from scratch. - Version Control: Use Git to track changes to code and analysis files.
Q: What is the difference between read.csv() and readr::read_csv()?
readr::read_csv() is the modern, tidyverse alternative with several key advantages:
- Speed: It is significantly faster, especially for large files.
- Output: It returns a
tibble, not a basedata.frame. - Reproducibility: It does not convert strings to factors by default and avoids altering column names, making scripts more stable.
- Type Guessing: It has a more robust algorithm for guessing column types and provides clear feedback if issues arise.
Q: Briefly explain the Grammar of Graphics in ggplot2.
The Grammar of Graphics is a theory that describes a plot as a set of layered components. In ggplot2, these are:
- Data: The dataset being plotted.
- Aesthetics (
aes): A mapping of data variables to visual properties (e.g.,xposition,yposition,color,size). - Geometries (
geom_): The geometric objects that represent the data (e.g.,geom_pointfor scatter plots,geom_barfor bar charts). - Facets: Create subplots for different subsets of the data.
- Coordinates: The coordinate system used (e.g., Cartesian, polar).
- Theme: Controls the non-data visual elements (e.g., fonts, background color). By combining these components, you can build a vast array of custom visualizations.
Final Advice
Section titled “Final Advice”Beyond technical questions, be prepared to discuss projects you’ve worked on. Explain the problem, how you used R to solve it, and what challenges you faced. Confidence in your problem-solving process is as important as knowing specific function names. Good luck!