Skip to content

R Basics and Data Types Interview Questions for R Programming

25 R Basics and Data Types questions with answers for r programming roles — 11 easy, 9 medium, 5 hard.

About R Basics and Data Types

Start with how R works: atomic types, vectors, coercion, missing values, factors, packages and the RStudio workflow. These fundamentals, along with concepts like vectorization, recycling, lazy evaluation and copy-on-modify, explain most of the errors and performance issues that interviewers ask about, so a clear grasp here makes every later topic easier.

Sheet progressStart 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 and why is it popular for data analysis?

Save to ▾
Show answer
R is an open-source language and environment built for statistics, data analysis and graphics. It is popular because of CRAN, which hosts over 20,000 packages, strong visualization with ggplot2 and built-in statistical functions. Analysts, biostatisticians and data scientists use it for reporting, modelling and research. For example, a pharma analytics team may use R for clinical trial analysis because many statistical methods are first released as R packages.
02

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

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

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

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

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

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
08

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
09

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

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$')
11

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

Explain the difference between NA, NULL and NaN in R.

Save to ▾
Show answer
NA means a missing value and has a type, such as NA_integer_ or NA_character_. NULL means the absence of an object, has length 0 and disappears when combined with c(). NaN means not a number, the result of undefined maths like 0/0. is.na() returns TRUE for both NA and NaN, while is.nan() is TRUE only for NaN. For example, length(c(1, NULL, 3)) is 2 but length(c(1, NA, 3)) is 3.
13

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

What is vectorization in R and why does it matter?

Save to ▾
Show answer
Vectorization means applying an operation to a whole vector at once instead of looping over elements. Most R functions, like +, sqrt() and ifelse(), are vectorized and implemented in C, so they are much faster than R-level for loops. For example, prices * 1.18 adds 18 percent GST to every price in one step. Writing vectorized code is the first optimization an R developer should try before parallel processing or Rcpp.
15

What is the recycling rule in R?

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

Your R script works on your laptop but fails on a colleague's machine with 'could not find function'. What do you check?

Save to ▾
Show answer
First I check that the package providing the function is installed and loaded with library() at the top of the script, not only in my interactive session. Then I compare R and package versions using sessionInfo(), because functions get renamed or deprecated. To prevent this, I use renv to snapshot exact package versions into a lockfile, so the colleague runs renv::restore() and gets the same environment. Namespacing calls like dplyr::filter() also avoids masking conflicts.
17

Reading a 2 GB CSV file with read.csv() is very slow. What would you do?

Save to ▾
Show answer
read.csv() is single-threaded and guesses types slowly. I would switch to data.table::fread() or readr::read_csv(), which are many times faster and multi-threaded. I would read only the needed columns with the select argument and set column types explicitly. If the file is reused, I convert it once to a binary format like Parquet with the arrow package, which loads in seconds and supports reading just a subset of columns.
18

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

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

Tell me about a time you automated a manual report.

Save to ▾
Show answer
Situation: my team spent two days every month building a sales report in Excel. Task: I was asked to reduce the effort. Action: I wrote an R script that pulled data from the database with DBI, cleaned it with dplyr, created charts with ggplot2 and rendered a Quarto report scheduled through cron. Result: the report ran in ten minutes, copy-paste errors disappeared and the team used the saved time for deeper analysis.
21

Explain environments and lexical scoping in R.

Save to ▾
Show answer
An environment is a collection of name-value bindings with a pointer to a parent environment. R uses lexical scoping: when a function looks up a variable, it searches its own environment, then the environment where it was defined, up through the global environment and attached packages. So a function defined inside another can read the outer function's variables, which enables closures. The <<- operator modifies a binding in a parent environment and should be used sparingly.
22

What is lazy evaluation in R?

Save to ▾
Show answer
R evaluates function arguments lazily, only when they are first used inside the function body. Arguments are stored as promises holding the expression and its environment. For example, f <- function(x, y) x * 2 works with f(5, stop('error')) because y is never touched. Lazy evaluation enables defaults that depend on other arguments and non-standard evaluation in dplyr, but it can surprise you when creating closures in a loop, which force() fixes.
23

What does copy-on-modify mean in R and how does it affect performance?

Save to ▾
Show answer
When you assign y <- x, both names point to the same object, and R makes a copy only when one of them is modified. tracemem() shows when copies happen. This is why growing a vector in a loop with x <- c(x, value) is slow, because each step can copy the whole vector. Preallocating with vector('numeric', n), using vectorized functions or data.table's modify-by-reference avoids repeated copies and memory spikes.
24

Your R session runs out of memory while processing a large dataset. What steps do you take?

Save to ▾
Show answer
I check object sizes with lobstr::obj_size() and remove large intermediates with rm() followed by gc(). I load only the needed columns and use data.table, which modifies by reference without copies. For data larger than RAM, I push computation into a database through dbplyr, or use arrow with Parquet files so filters and aggregations run before data enters R memory. Chunked reading with readr::read_csv_chunked() is another option for one-pass jobs.
25

What are the differences between S3, S4 and R6 classes?

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

Frequently asked questions

How important is R Basics and Data Types in R Programming interviews?

Start with how R works: atomic types, vectors, coercion, missing values, factors, packages and the RStudio workflow. These fundamentals, along with concepts like vectorization, recycling, lazy evaluation and copy-on-modify, explain most of the errors and performance issues that interviewers ask about, so a clear grasp here makes every later topic easier.

How should I use the R Basics and Data Types sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.