R Programming Study Notes
R Programming Study Notes
Page 1 of 31
R Programming for Data Science — Study Notes
📝 EXAM TIP
Exam questions often ask about the course scope. Remember: R is a tool here — the focus
is on algorithms, math, and data science concepts, NOT big data infrastructure.
1.2 What is R?
📝 DEFINITION
R is an open-source programming language and statistical computing environment used for
data analysis, machine learning, and research.
Page 2 of 31
R Programming for Data Science — Study Notes
• Machine Learning
• Academic Research
📝 INTERVIEW NOTE
R is open-source (free), cross-platform, and has thousands of packages via CRAN
(Comprehensive R Archive Network). It is the industry standard for statistical computing
alongside Python.
An IDE combines multiple tools (editor, console, file manager, package manager, help system) into a
single application — making programming easier than using plain text editors.
Files Tab Browse files and directories Navigate your project folder
Plots Tab Display graphs and charts All plot() / ggplot() output appears
here
📝 EXAM TIP
The Console pane is where R executes code. The Environment pane shows currently stored
variables. Plots are always shown in the Plots tab.
Page 3 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
Always set your working directory before reading or writing files. Use forward slashes (/)
even on Windows, or double backslashes (\\).
Example Script:
a <- 11
b <- a * 10
print(c(a, b))
Running Code:
Run single line Ctrl + Enter (cursor on that line)
Page 4 of 31
R Programming for Data Science — Study Notes
📝 EXAM TIP
source() runs an entire script file. echo = TRUE prints each command before its output —
useful for debugging or demonstrations.
3.3 Comments
📝 DEFINITION
A comment is text in the code that R ignores during execution. Comments exist only to
explain and document code for human readers.
Syntax:
# This is a single-line comment
📝 IMPORTANT
R does NOT support multi-line block comments like /* */ in other languages. Use # at the
start of each line, or use Ctrl+Shift+C in RStudio to toggle comments on selected lines.
❌ COMMON ERROR
Clearing the console only clears the display. It does NOT delete variables stored in memory.
Variables remain in the Environment pane.
Page 5 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
rm(list = ls()) completely clears the workspace. Use with caution — there is no undo.
Naming Rules:
• Must start with a letter (not a number or symbol)
• Can contain: letters, numbers, _ (underscore), . (dot)
• Case-sensitive: myVar and myvar are different
Page 6 of 31
R Programming for Data Science — Study Notes
Valid Examples:
x <- 5
data_value <- 10
score.1 <- 90
myVariable <- TRUE
Invalid Examples:
2x <- 5 # ERROR: starts with a number
@value <- 10 # ERROR: starts with special character
❌ COMMON ERROR
Starting a variable name with a number is the most common naming error. Always start with
a letter.
📝 EXAM TIP
pi, letters, LETTERS, [Link], and [Link] are all built-in. You do not need to assign
them.
Page 7 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
[Link]() truncates (does not round). [Link](3.9) returns 3, not 4.
📝 EXAM TIP
Know the difference between typeof() (returns the internal type) and class() (returns the
object class). For numeric vectors, typeof() returns 'double' while class() returns 'numeric'.
PART 5 — Vectors
Page 8 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
All elements in a vector MUST be of the same type. If you mix types, R automatically
converts everything to the most flexible type (logical < integer < double < complex <
character).
📝 EXAM TIP
Vectors are 1-indexed in R (unlike Python which is 0-indexed). x[1] gives the first element.
PART 6 — Lists
Creating a List:
employee <- list(
ID = c(1, 2, 3),
Name = c("A", "B", "C"),
Count = 3
)
Page 9 of 31
R Programming for Data Science — Study Notes
Modifying a List:
# Change an existing element
employee$Count <- 4
❌ COMMON ERROR
Using single brackets [ ] returns a list, not the element. Use [[ ]] or $ to get the actual content.
📝 EXAM TIP
Lists are the most flexible data structure in R. Functions that return multiple values typically
return a list.
Each column in a data frame is a vector. All columns must have the same number of rows. Columns
can be of different types (unlike a matrix).
Page 10 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
By default, strings in data frames are treated as factors (categorical variables). To prevent
this use stringsAsFactors = FALSE in [Link]().
df <- [Link](
Name = c("Alice", "Bob"),
stringsAsFactors = FALSE # Keep strings as characters
)
Page 11 of 31
R Programming for Data Science — Study Notes
df$Name
# Delete column 1
df <- df[, -1]
📝 EXAM TIP
rbind() adds rows (R = Row). cbind() adds columns (C = Column). Negative indexing
removes elements — df[-3,] removes row 3.
📝 DEFINITION
Recasting (or reshaping) is the process of transforming data between wide format and long
format. It changes how data is organized without changing the data itself.
B 78 92
A Science 85
B Math 78
B Science 92
Syntax:
melt(
data, # The data frame
[Link], # Columns to keep as identifiers (e.g., 'Name')
Page 13 of 31
R Programming for Data Science — Study Notes
# Example:
melted <- melt(df, [Link]='Name', [Link]=c('Math','Science'))
# Example:
wide <- dcast(melted, Name ~ variable, [Link]='value')
📝 EXAM TIP
melt() = wide to long. dcast() = long to wide. Think of melt() as 'melting' columns down into
rows, like melting ice into water.
9.1 Overview
📝 DEFINITION
dplyr is a powerful R package for data manipulation. It provides intuitive verbs (functions) for
common data operations.
Page 14 of 31
R Programming for Data Science — Study Notes
[Link]("dplyr")
library(dplyr)
Right Join right_join(df1, df2, by='ID') All rows from df2; matching rows
from df1. Non-matches become
NA.
Inner Join inner_join(df1, df2, by='ID') Only rows that have matching
keys in BOTH df1 and df2.
📝 EXAM TIP
LEFT JOIN is the most common join. Inner join is the most restrictive (only matched rows). A
full outer join keeps ALL rows from both tables — not directly available in dplyr (use merge()
with all=TRUE instead).
Page 15 of 31
R Programming for Data Science — Study Notes
📝 INTERVIEW NOTE
SQL equivalents: left_join = LEFT JOIN, right_join = RIGHT JOIN, inner_join = INNER JOIN.
dplyr functions translate directly to SQL concepts.
PART 10 — Operators
- Subtraction 5-3 2
* Multiplication 5*3 15
%% Modulo (remainder) 5 %% 3 2
== Equal to 2 == 2 TRUE
Page 16 of 31
R Programming for Data Science — Study Notes
2 > 3 # FALSE
5 == 5 # TRUE
4 != 3 # TRUE
❌ COMMON ERROR
Use == for comparison, NOT =. The single = is for assignment in function arguments.
Confusing = and == is one of the most common bugs in R.
PART 11 — Matrices
📝 IMPORTANT
Page 17 of 31
R Programming for Data Science — Study Notes
By default, byrow = FALSE, meaning R fills columns first (top to bottom). Set byrow = TRUE
to fill rows first (left to right) — this is the more intuitive format.
Page 18 of 31
R Programming for Data Science — Study Notes
# Element-wise multiplication
A * B
# Transpose
t(A)
# Determinant
det(A)
# Inverse
solve(A)
📝 IMPORTANT
Use %*% for matrix multiplication (linear algebra). Using * gives element-wise multiplication
(different result). For A %*% B, the number of columns in A must equal the number of rows
in B.
📝 EXAM TIP
Matrix indexing: A[row, col]. To get all rows, leave row blank: A[, col]. To get all columns,
leave col blank: A[row, ].
📝 INTERVIEW NOTE
The identity matrix is the matrix equivalent of the number 1. Multiplying any matrix by the
identity matrix returns the original: A %*% I = A. The inverse A^(-1) satisfies A %*% solve(A)
= I.
PART 12 — Functions in R
Page 19 of 31
R Programming for Data Science — Study Notes
📝 IMPORTANT
In R, the last evaluated expression in a function body is automatically returned. You do not
need to write return() explicitly, but it is good practice for clarity.
Page 20 of 31
R Programming for Data Science — Study Notes
return(result)
}
📝 EXAM TIP
Anonymous functions are especially useful with apply(), lapply(), sapply(), and mapply()
when a simple transformation is needed without defining a full named function.
Page 21 of 31
R Programming for Data Science — Study Notes
13.2 apply()
📝 DEFINITION
apply() applies a function to the rows (margin=1) or columns (margin=2) of a matrix.
apply(matrix, margin, function)
M <- matrix(1:9, 3, 3)
apply(M, 1, sum) # Sum of each row: 12 15 18
apply(M, 2, sum) # Sum of each col: 6 15 24
13.3 lapply()
📝 DEFINITION
lapply() applies a function to each element of a list and always returns a list.
my_list <- list(a=1:5, b=6:10)
lapply(my_list, mean)
# Returns a list: $a = 3, $b = 8
13.4 mapply()
📝 DEFINITION
mapply() applies a function to corresponding elements of multiple lists or vectors
simultaneously.
mapply(function, list1, list2, ...)
13.5 tapply()
Page 22 of 31
R Programming for Data Science — Study Notes
📝 DEFINITION
tapply() applies a function to subsets of a vector, grouped by a factor (categorical variable).
tapply(vector, group, function)
📝 EXAM TIP
Memory trick: apply=matrix, lapply=list (returns List), sapply=simplified list, tapply=table
grouped (like a pivot table), mapply=multiple inputs.
14.1 if Statement
📝 DEFINITION
The if statement executes a block of code only when a condition is TRUE.
if (condition) {
# code runs when condition is TRUE
}
# Example:
x <- 10
if (x > 5) {
print("x is greater than 5")
}
Page 23 of 31
R Programming for Data Science — Study Notes
# Example:
x <- 3
if (x %% 2 == 0) {
print("Even")
} else {
print("Odd")
}
# else-if chain:
if (x > 0) {
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}
# Example: print 1 to 5
for (i in 1:5) {
print(i)
}
# Output: 1 2 3 4 5
Page 24 of 31
R Programming for Data Science — Study Notes
# Example: count up to 5
count <- 1
while (count <= 5) {
print(count)
count <- count + 1
}
# Output: 1 2 3 4 5
❌ COMMON ERROR
Forgetting to update the loop variable inside a while loop creates an infinite loop. Always
ensure the condition eventually becomes FALSE.
📝 EXAM TIP
Use for when you know the number of iterations in advance. Use while when the termination
condition depends on computed values.
PART 15 — Graphics in R
15.1 Overview
R provides powerful built-in graphics functions. Plots appear in the Plots tab of RStudio.
Page 25 of 31
R Programming for Data Science — Study Notes
# type options:
# "p" = points (default scatter)
# "l" = lines
# "b" = both points and lines
# "o" = overlaid points and lines
# With labels
Page 26 of 31
R Programming for Data Science — Study Notes
barplot(
c(7, 12, 28),
[Link] = c("March", "April", "May"),
main = "Monthly Sales",
col = c("red", "blue", "green")
)
"l" Lines
📝 INTERVIEW NOTE
ggplot2 is the professional-grade plotting library in R (Grammar of Graphics). It is more
powerful and flexible than base R graphics. Always prefer ggplot2 for publication-quality
plots.
📝 EXAM TIP
Know the three main plot types: scatter (plot), line (plot with type='l'), and bar (barplot). Also
know how to add titles (main=), axis labels (xlab=, ylab=), and colors (col=).
Page 27 of 31
R Programming for Data Science — Study Notes
Page 28 of 31
R Programming for Data Science — Study Notes
reshape2 Functions
melt(data, [Link], [Link]) Wide → Long format
dplyr Functions
mutate(df, new_col = expr) Add/transform columns
Apply Family
apply(matrix, 1, fn) Apply fn to each ROW of matrix
Page 29 of 31
R Programming for Data Science — Study Notes
for (i in sequence) { }
while (cond) { }
Graphics
plot(x, y) Scatter plot
hist(x) Histogram
Category Operators
Arithmetic + - * / %% %/% ^
Sequence 1:n
Important Libraries
Page 30 of 31
R Programming for Data Science — Study Notes
Page 31 of 31