0% found this document useful (0 votes)
7 views31 pages

R Programming Study Notes

This document serves as a comprehensive study guide for a beginner-level course on R programming for data science, covering essential topics such as data types, functions, and control flow. It emphasizes the use of R as a tool for implementing data science concepts, including linear algebra, statistics, and machine learning, while outlining the structured problem-solving workflow. Additionally, it provides practical guidance on using RStudio, creating scripts, and working with various data structures like vectors, lists, and data frames.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views31 pages

R Programming Study Notes

This document serves as a comprehensive study guide for a beginner-level course on R programming for data science, covering essential topics such as data types, functions, and control flow. It emphasizes the use of R as a tool for implementing data science concepts, including linear algebra, statistics, and machine learning, while outlining the structured problem-solving workflow. Additionally, it provides practical guidance on using RStudio, creating scripts, and working with various data structures like vectors, lists, and data frames.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

R Programming for Data Science — Study Notes

R PROGRAMMING FOR DATA


SCIENCE
Complete Study Notes

University Exams | Assignments | Quick Revision | Long-Term Reference

Data Types Vectors & Lists Data Frames Matrices

Functions Apply Family Control Flow Graphics

Page 1 of 31
R Programming for Data Science — Study Notes

PART 1 — Introduction to Data Science and R

1.1 Course Objective


This course is a beginner-level introduction to data science with substantial mathematical and
conceptual learning. It uses R as the programming platform to implement data science concepts — R is
the tool, not the subject.

The Course Focuses On:


• Linear Algebra
• Statistics
• Optimization
• Machine Learning

Topics NOT Covered (Out of Scope):


• Big Data Technologies such as Hadoop, MapReduce

The Structured Problem-Solving Workflow:


1. Understand the data problem
2. Break it into smaller components
3. Choose an appropriate algorithm
4. Implement the solution
5. Validate assumptions
6. Generate reports

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

R runs on: Windows, Linux, macOS — it is fully cross-platform.

R is Widely Used In:


• Data Science
• Statistics

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.

PART 2 — RStudio: The IDE for R

2.1 What is RStudio?


📝 DEFINITION
RStudio is an Integrated Development Environment (IDE) for R. It provides a graphical
interface to write, run, and debug R code.

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.

2.2 RStudio Interface Components


RStudio is divided into several panes, each serving a distinct purpose:

Pane / Tab Purpose Key Detail


Console Execute commands; display Type code directly here for quick
output testing

Environment Show variables/objects in Lets you inspect values without


memory printing

History View previously executed Use arrow keys in console to re-


commands run old commands

Files Tab Browse files and directories Navigate your project folder

Plots Tab Display graphs and charts All plot() / ggplot() output appears
here

Packages Tab Install and load libraries GUI alternative to


[Link]()

Help Tab View function documentation Press F1 on any function name

📝 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

PART 3 — Working with R: Setup and Basics

3.1 Working Directory


📝 DEFINITION
The working directory is the default folder where R reads files from and saves files to. Think
of it as R's 'home base' for a session.

Set the Working Directory


# Set to a specific folder
setwd("C:/Data")

# Check current working directory


getwd()

📝 IMPORTANT
Always set your working directory before reading or writing files. Use forward slashes (/)
even on Windows, or double backslashes (\\).

3.2 Creating and Running an R Script


An R Script is a plain text file with a .R extension that stores your code for repeated use.

Creating a Script in RStudio:


7. Go to File
8. Select New File
9. Choose R Script

Example Script:
a <- 11
b <- a * 10
print(c(a, b))

Output: [1] 11 110

Running Code:
Run single line Ctrl + Enter (cursor on that line)

Run entire script source("file.R")

Page 4 of 31
R Programming for Data Science — Study Notes

Run script + show commands source("file.R", echo = TRUE)

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

Why Comments Matter:


• Improve code readability
• Explain the purpose of complex operations
• Document algorithms and logic for future reference

Syntax:
# This is a single-line comment

a <- 5 # Inline comment after code

# To comment/uncomment multiple lines at once:


# Select lines, then press Ctrl + Shift + C

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

3.4 Console Operations


Clearing the Console:
# Keyboard shortcut:
Ctrl + L

❌ COMMON ERROR
Clearing the console only clears the display. It does NOT delete variables stored in memory.
Variables remain in the Environment pane.

3.5 Removing Variables

Page 5 of 31
R Programming for Data Science — Study Notes

# Remove a single variable


rm(a)

# Remove all variables from memory


rm(list = ls())

# ls() lists all current variable names

📝 IMPORTANT
rm(list = ls()) completely clears the workspace. Use with caution — there is no undo.

3.6 Saving and Loading Workspace


R allows you to save your working environment (all variables) to a file so you can continue later.
# Save a specific variable
save(a, file = "[Link]")

# Save the entire workspace (all variables)


[Link]()

# Load a previously saved workspace


load("[Link]")
The default workspace file is .RData in the working directory. RStudio asks to save/restore it when you
close/open.

PART 4 — Variables and Data Types

4.1 Variable Naming Rules


📝 DEFINITION
A variable is a named storage location in memory that holds a value. In R, the assignment
operator is <- (left arrow).

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.

4.2 Built-in Constants


R provides several pre-defined constants you can use immediately:
pi # 3.141593
letters # a, b, c, ..., z (lowercase)
LETTERS # A, B, C, ..., Z (uppercase)
[Link] # January, February, ..., December
[Link] # Jan, Feb, ..., Dec

📝 EXAM TIP
pi, letters, LETTERS, [Link], and [Link] are all built-in. You do not need to assign
them.

4.3 Basic Data Types in R


Every value in R has a type. Understanding types is essential because operations behave differently
across types.

Data Type Description Example typeof() returns


Logical Boolean: TRUE or TRUE, FALSE logical
FALSE

Integer Whole numbers (L 5L, -3L integer


suffix)

Numeric Decimal / floating-point 3.14, -0.5 double


numbers

Complex Numbers with imaginary 2+3i complex


part

Character Text strings (in quotes) "Hello", 'world' character

Page 7 of 31
R Programming for Data Science — Study Notes

Checking a Variable's Type:


x <- 3.14
typeof(x) # Returns 'double'

# Check for specific types:


[Link](x) # TRUE
[Link](x) # FALSE
[Link](x) # FALSE
[Link](x) # FALSE

Type Conversion (Coercion):


You can convert between types using as.* functions:
[Link]("3.14") # Converts string to number: 3.14
[Link](42) # Converts number to string: "42"
[Link](3.7) # Truncates to integer: 3
[Link](5) # Converts to complex: 5+0i
[Link](0) # 0 -> FALSE; any non-zero -> TRUE

📝 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

5.1 What is a Vector?


📝 DEFINITION
A vector is R's most fundamental data structure. It is an ordered collection of elements all of
the same data type. Even a single value is a vector of length 1 in R.

Creating a Vector with c():


# c() stands for 'concatenate'
x <- c(2.3, 4.5, 6.7, 8.9)

numbers <- c(1, 2, 3, 4)

Page 8 of 31
R Programming for Data Science — Study Notes

words <- c("apple", "banana", "cherry")

flags <- c(TRUE, FALSE, TRUE)

Using the Colon Operator to Create Integer Sequences:


1:10 # Creates: 1 2 3 4 5 6 7 8 9 10
5:1 # Counts down: 5 4 3 2 1

Useful Vector Functions:


length(x) # Number of elements
sum(x) # Sum of all elements
mean(x) # Average
min(x) # Minimum value
max(x) # Maximum value
sort(x) # Sort ascending

📝 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

6.1 What is a List?


📝 DEFINITION
A list is a collection of objects that can be of different data types. Unlike vectors, lists can
hold mixed types — numbers, characters, vectors, even other 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

Accessing List Elements:


# Using the $ operator (by name) — RECOMMENDED
employee$Name # Returns: 'A' 'B' 'C'

# Using double brackets [[]] (by index)


employee[[1]] # Returns the first element (ID vector)

# Using double brackets by name


employee[["Name"]] # Returns: 'A' 'B' 'C'

Modifying a List:
# Change an existing element
employee$Count <- 4

# Add a new element


employee$Department <- "HR"

Single brackets [] Returns a sub-list (still a list)

Double brackets [[]] Returns the actual element inside

$ operator Returns the element (same as [[]])

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

PART 7 — Data Frames

7.1 What is a Data Frame?


📝 DEFINITION
A data frame is R's primary structure for tabular data. It is similar to a spreadsheet or
database table — rows represent observations, columns represent variables (features).

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

7.2 Creating a Data Frame


df <- [Link](
ID = c(1, 2, 3),
Name = c("Alice", "Bob", "Carol"),
Age = c(25, 30, 28)
)

# View the data frame


print(df)

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

7.3 Importing Data into a Data Frame


# Import from a text file
df <- [Link]("[Link]")

# Import from CSV (most common)


df <- [Link]("[Link]")

7.4 Accessing Data in a Data Frame


Data frames use df[row, column] indexing. Leave row or column blank to select all.
# Access rows 1 and 2 (all columns)
df[1:2, ]

# Access columns 1 and 2 (all rows)


df[, 1:2]

# Access specific cell: row 2, column 2


df[2, 2]

# Access column by name

Page 11 of 31
R Programming for Data Science — Study Notes

df$Name

# Access column by name (bracket notation)


df[, "Name"]

7.5 Editing a Data Frame


Adding Rows and Columns:
# Add a new row
new_row <- [Link](ID=4, Name='Dave', Age=22)
df <- rbind(df, new_row) # rbind = row bind

# Add a new column


new_col <- c(90, 85, 78, 95)
df <- cbind(df, Score=new_col) # cbind = column bind

Deleting Rows and Columns:


# Delete row 3 (negative index = exclude)
df <- df[-3, ]

# Delete column 1
df <- df[, -1]

Subsetting with Conditions:


# Select rows where Age > 25
subset(df, Age > 25)

# Equivalent using indexing


df[df$Age > 25, ]

📝 EXAM TIP
rbind() adds rows (R = Row). cbind() adds columns (C = Column). Negative indexing
removes elements — df[-3,] removes row 3.

PART 8 — Recasting Data (reshape2)

8.1 What is Recasting?


Page 12 of 31
R Programming for Data Science — Study Notes

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

Wide Format Each variable has its own column — typical


spreadsheet layout

Long Format Each row is one observation of one variable —


needed for many analyses

# Install the package (run once)


[Link]("reshape2")

# Load the library


library(reshape2)

8.2 melt() — Wide to Long


📝 DEFINITION
melt() converts data from wide format to long format by turning multiple value columns into
key-value rows.

Before melt() (wide format):


Name Math Science
A 90 85

B 78 92

After melt() (long format):


Name Subject Marks
A Math 90

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

[Link] # Columns to collapse into rows (e.g., 'Math','Science')


)

# Example:
melted <- melt(df, [Link]='Name', [Link]=c('Math','Science'))

# The new columns are automatically named 'variable' and 'value'

8.3 dcast() — Long to Wide


📝 DEFINITION
dcast() is the reverse of melt(). It converts long format back to wide format using a formula.
dcast(
data, # Melted data frame
formula, # row_variable ~ column_variable
[Link] # Column containing the values
)

# Example:
wide <- dcast(melted, Name ~ variable, [Link]='value')

8.4 recast() — Melt + Cast in One Step


📝 DEFINITION
recast() combines melt() and dcast() into a single function call for convenience.
recast(data, formula)

📝 EXAM TIP
melt() = wide to long. dcast() = long to wide. Think of melt() as 'melting' columns down into
rows, like melting ice into water.

PART 9 — dplyr: Data Manipulation

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)

9.2 mutate() — Creating New Variables


📝 DEFINITION
mutate() adds new columns to a data frame based on calculations from existing columns.
# Create a new column 'log_BP' as the log of column 'BP'
df <- mutate(df, log_BP = log(BP))

# Create multiple new columns at once


df <- mutate(df,
log_BP = log(BP),
BP_squared = BP^2
)

9.3 Joining Data Frames


📝 DEFINITION
Joins combine two data frames based on a common key column (like a shared ID).

Join Type Function What It Returns


Left Join left_join(df1, df2, by='ID') All rows from df1; matching rows
from df2. Non-matches become
NA.

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.

# Left Join example


result <- left_join(df1, df2, by='ID')

# Inner Join example


result <- inner_join(df1, df2, by='ID')

📝 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

10.1 Arithmetic Operators


Operator Name Example Result
+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/3 1.667

%% Modulo (remainder) 5 %% 3 2

%/% Integer division 5 %/% 3 1

^ Exponentiation 5^3 125

Operator Precedence (highest to lowest):


10. () — Parentheses (override all else)
11. ^ — Exponentiation
12. / — Division
13. * — Multiplication
14. + — Addition
15. - — Subtraction
📝 EXAM TIP
Exponentiation (^) has higher precedence than multiplication (*) in R. Example: 2 * 3 ^ 2 = 2
* 9 = 18, not 36.

10.2 Logical / Comparison Operators


Operator Meaning Example Result
< Less than 2<3 TRUE

<= Less than or equal 3 <= 3 TRUE

> Greater than 2>3 FALSE

>= Greater than or equal 4 >= 3 TRUE

== Equal to 2 == 2 TRUE

Page 16 of 31
R Programming for Data Science — Study Notes

!= Not equal to 2 != 3 TRUE

& AND (element-wise) TRUE & FALSE FALSE

| OR (element-wise) TRUE | FALSE TRUE

! NOT !TRUE FALSE

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

11.1 What is a Matrix?


📝 DEFINITION
A matrix is a two-dimensional data structure in R that holds elements of the same data type
arranged in rows and columns. It is the foundation of linear algebra in R.

11.2 Creating a Matrix


matrix(
data, # Values to fill in
nrow, # Number of rows
ncol, # Number of columns
byrow = TRUE # Fill by row (default: byrow=FALSE fills by column)
)

# Example: 3x3 matrix filled row by row


A <- matrix(1:9, nrow=3, ncol=3, byrow=TRUE)
# Result:
# [,1] [,2] [,3]
# 1 2 3
# 4 5 6
# 7 8 9

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

11.3 Special Matrices


# Diagonal matrix (non-zero only on main diagonal)
diag(c(4, 5, 6))
# Result:
# 4 0 0
# 0 5 0
# 0 0 6

# Identity matrix (diagonal of 1s)


diag(1, 3, 3)
# Result:
# 1 0 0
# 0 1 0
# 0 0 1

11.4 Matrix Dimensions and Properties


dim(A) # Returns c(rows, cols) — e.g., c(3,3)
nrow(A) # Number of rows
ncol(A) # Number of columns
length(A) # Total number of elements (rows * cols)

11.5 Accessing Matrix Elements


# Access element at row 2, column 3
A[2, 3]

# Access entire row 1


A[1, ]

# Access entire column 2


A[, 2]

# Access a sub-matrix (rows 1-2, columns 1-2)


A[1:2, 1:2]

Page 18 of 31
R Programming for Data Science — Study Notes

11.6 Matrix Operations


# Element-wise addition
A + B

# Element-wise multiplication
A * B

# TRUE matrix multiplication (dot product)


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

12.1 What is a Function?


📝 DEFINITION
A function is a named, reusable block of code that performs a specific task. Functions take
inputs (arguments), process them, and return an output.

Page 19 of 31
R Programming for Data Science — Study Notes

12.2 Creating a Function


# Basic syntax
function_name <- function(argument1, argument2) {
# body: operations on arguments
result <- argument1 + argument2
return(result) # explicitly return (optional)
}

# Example: square a number


f <- function(x) {
x^2
}

# Call the function


f(5) # Returns 25

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

12.3 Default Arguments


📝 DEFINITION
Default arguments provide fallback values for parameters. If the caller does not supply a
value, the default is used.
# x has default value of 10
f <- function(x = 10) {
x^2
}

f() # Returns 100 (uses default x=10)


f(5) # Returns 25 (overrides default)

12.4 Returning Multiple Values


R functions can only directly return one object. To return multiple values, wrap them in a list.
box_properties <- function(l, w, h) {
volume <- l * w * h
surface <- 2 * (l*w + w*h + h*l)
result <- list(volume=volume, surface=surface)

Page 20 of 31
R Programming for Data Science — Study Notes

return(result)
}

out <- box_properties(3, 4, 5)


out$volume # 60
out$surface # 94

12.5 Inline (Anonymous) Functions


📝 DEFINITION
An anonymous function is a function without a name, used inline when you need a quick
one-off operation.
# Inline function — no name assigned
function(x) x^2 + 4*x + 4

# Commonly used with apply family:


sapply(1:5, function(x) x^2)
# Returns: 1 4 9 16 25

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

PART 13 — The Apply Family

13.1 Why the Apply Family?


The apply family replaces loops for applying a function repeatedly to rows, columns, or elements. This
is more efficient and idiomatic in R.

Function Input Use Case Output


apply() Matrix / Array Apply function to rows or Vector or matrix
columns

lapply() List or Vector Apply function to each Always a list


element

sapply() List or Vector Same as lapply but Vector, matrix, or list


simplified output

mapply() Multiple lists Apply function over List or vector


multiple inputs

Page 21 of 31
R Programming for Data Science — Study Notes

tapply() Vector + groups Apply function grouped Named array


by a factor

13.2 apply()
📝 DEFINITION
apply() applies a function to the rows (margin=1) or columns (margin=2) of a matrix.
apply(matrix, margin, function)

# margin = 1 → apply to each ROW


# margin = 2 → apply to each COLUMN

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, ...)

# Example: compute l * w for paired dimensions


lengths <- c(2, 4, 6)
widths <- c(3, 5, 7)
mapply(function(l, w) l*w, lengths, widths)
# Returns: 6 20 42

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)

# Example: mean salary by department


salary <- c(50000, 60000, 70000, 80000)
dept <- c("HR", "IT", "HR", "IT")
tapply(salary, dept, mean)
# HR: 60000 IT: 70000

📝 EXAM TIP
Memory trick: apply=matrix, lapply=list (returns List), sapply=simplified list, tapply=table
grouped (like a pivot table), mapply=multiple inputs.

PART 14 — Control Structures

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

14.2 if-else Statement


📝 DEFINITION
The if-else statement provides an alternative block to run when the condition is FALSE.
if (condition) {
# runs when TRUE
} else {
# runs when FALSE

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

14.3 for Loop


📝 DEFINITION
The for loop iterates over each element in a sequence and executes the loop body for each
element.
for (variable in sequence) {
# code to repeat
}

# Example: print 1 to 5
for (i in 1:5) {
print(i)
}
# Output: 1 2 3 4 5

# Loop over a vector


fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
print(fruit)
}

Page 24 of 31
R Programming for Data Science — Study Notes

break — Exit a Loop Early:


for (i in 1:10) {
if (i == 5) {
break # Exit loop when i reaches 5
}
print(i)
}
# Output: 1 2 3 4

14.4 while Loop


📝 DEFINITION
The while loop repeats a block of code as long as a condition remains TRUE.
while (condition) {
# code repeats while condition is TRUE
}

# 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

15.2 Scatter Plot


📝 DEFINITION
A scatter plot displays the relationship between two continuous variables. Each point
represents one observation.
# Basic scatter plot
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 1, 3, 5)
plot(x, y)

# With labels and title


plot(x, y,
main = "Scatter Plot",
xlab = "X Axis",
ylab = "Y Axis",
col = "blue",
pch = 19 # Point shape (19 = solid circle)
)

15.3 Line Plot


📝 DEFINITION
A line plot connects data points with lines, useful for showing trends over time.
# type = "l" creates a line plot
plot(x, y, type = "l")

# type options:
# "p" = points (default scatter)
# "l" = lines
# "b" = both points and lines
# "o" = overlaid points and lines

15.4 Bar Plot


📝 DEFINITION
A bar plot displays categorical data with rectangular bars whose lengths represent values.
# Simple bar plot
barplot(c(7, 12, 28))

# 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")
)

Summary of plot() type Values:


"p" Points (scatter plot) — default

"l" Lines

"b" Both points and lines

"h" Histogram-like vertical lines

"s" Step function

📝 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

QUICK REVISION SHEET


R Programming for Data Science — All Key Functions, Operators, Libraries, Concepts

Essential Functions by Category

Workspace & Setup


setwd() / getwd() Set / get working directory

ls() List all variables in memory

rm(x) / rm(list=ls()) Remove variable / clear all

save(x, file="[Link]") Save variable to file

[Link]() Save entire workspace

load("[Link]") Load saved workspace

source("file.R") Run an R script file

Type Checking and Conversion


typeof(x) Internal type of x

class(x) Object class of x

[Link]() / [Link]() / Check specific type


[Link]()

[Link]() / [Link]() / Convert type


[Link]()

[Link]() / [Link]() Convert to logical / complex

Vector & Data Structure


c(...) Create a vector

1:n Integer sequence 1 to n

length(x) Length of vector

list(...) Create a list

[Link](...) Create a data frame

rbind(df, row) Add row to data frame

cbind(df, col) Add column to data frame

subset(df, cond) Filter rows by condition

Page 28 of 31
R Programming for Data Science — Study Notes

matrix(data, nrow, ncol, byrow) Create matrix

diag(x) Diagonal or identity matrix

dim() / nrow() / ncol() Matrix dimensions

t(A) Transpose matrix

det(A) / solve(A) Determinant / inverse

Data Import / Export


[Link]("[Link]") Read text file

[Link]("[Link]") Read CSV file (most common)

[Link](df, "[Link]") Write data frame to CSV

reshape2 Functions
melt(data, [Link], [Link]) Wide → Long format

dcast(data, formula, [Link]) Long → Wide format

recast(data, formula) Melt + cast in one step

dplyr Functions
mutate(df, new_col = expr) Add/transform columns

left_join(df1, df2, by='key') All df1 rows + matching df2

right_join(df1, df2, by='key') All df2 rows + matching df1

inner_join(df1, df2, by='key') Only matched rows

filter(df, condition) Filter rows (like subset)

select(df, col1, col2) Select specific columns

arrange(df, col) Sort rows

summarise(df, stat=fn(col)) Compute summary stats

group_by(df, col) Group for grouped operations

Apply Family
apply(matrix, 1, fn) Apply fn to each ROW of matrix

apply(matrix, 2, fn) Apply fn to each COLUMN of matrix

lapply(list, fn) Apply fn to each list element → list

sapply(list, fn) Like lapply → simplified output

mapply(fn, list1, list2) Apply fn to multiple lists element-wise

Page 29 of 31
R Programming for Data Science — Study Notes

tapply(vec, group, fn) Apply fn by group (like GROUP BY)

Control Structures (Syntax Quick-Reference)


if (cond) { } else { }

for (i in sequence) { }

while (cond) { }

break # Exit loop


next # Skip to next iteration (like 'continue' in Python)

Graphics
plot(x, y) Scatter plot

plot(x, y, type="l") Line plot

barplot(heights, [Link]=...) Bar chart

hist(x) Histogram

boxplot(x) Box plot

main="title", xlab="X", ylab="Y" Labels and title

col="blue", pch=19 Color and point shape

All Operators at a Glance

Category Operators
Arithmetic + - * / %% %/% ^

Assignment <- = (use <- preferred)

Comparison < <= > >= == !=

Logical & | ! && ||

Matrix multiply %*%

Sequence 1:n

Pipe (dplyr) |> or %>% (magrittr)

Important Libraries

Page 30 of 31
R Programming for Data Science — Study Notes

Library Purpose Key Functions


reshape2 Data reshaping melt(), dcast(), recast()

dplyr Data manipulation mutate(), filter(), select(), *_join()

ggplot2 Advanced visualization ggplot(), geom_point(),


geom_bar()

base R Built-in, no install needed plot(), apply(), matrix(),


[Link]()

Complete Topic Checklist

✓ R Introduction ✓ Variable Naming Rules


✓ RStudio Interface ✓ Data Types
✓ Working Directory ✓ Type Conversion
✓ Scripts & source() ✓ Vectors
✓ Comments ✓ Lists
✓ Console & Clearing ✓ Data Frames
✓ Workspace Save/Load ✓ Importing Data
✓ Removing Variables ✓ Subsetting
✓ Built-in Constants ✓ Recasting (melt/dcast)
✓ dplyr Joins ✓ Arithmetic Operators
✓ Logical Operators ✓ Matrices
✓ Functions ✓ Apply Family
✓ Control Structures ✓ Graphics
✓ Libraries

All topics from the course are covered in these notes.


Use the revision sheet above for last-minute exam preparation.

Page 31 of 31

You might also like