DSA 222R - R Programming for Data Science
Course Programme: DDA SEM 4
Welcome to your comprehensive study guide for R Programming! This document is designed
to take you from knowing absolutely nothing about R to scoring a distinction. We will use
simple language, real-life examples, and clear explanations.
Week 1: Introduction to R
Overview of R and its Applications
What is R? R is a programming language and a software environment used specifically for
statistical computing and graphics. Imagine Excel on steroids; while Excel is great for
organizing data, R is built to analyze massive amounts of data and create beautiful
visualizations automatically.
Applications of R:
• Business: Companies use R to analyze sales data, predict customer behavior, and
optimize pricing.
• Hospitals: Researchers use R to analyze patient data, study disease outbreaks, and
evaluate the effectiveness of new treatments.
• Schools: Educators use R to analyze student performance data and identify areas
where students struggle.
• NGOs: Organizations use R to track the impact of their projects, analyze survey data
from the communities they serve, and report findings to donors.
Setting Up R and RStudio
What is R vs. RStudio? Think of R as the engine of a car. It does the heavy lifting and
calculations. Think of RStudio as the dashboard and steering wheel. It is an Integrated
Development Environment (IDE) that makes it much easier to use the R engine. You need to
install R first, then install RStudio.
RStudio Interface
When you open RStudio, you will see four main panels:
1 Console (Bottom Left): This is where you type commands and see immediate results.
It's like a chat window with the computer.
2 Script Editor (Top Left): This is where you write your code to save it for later. It's
like a Word document for your code.
3 Environment (Top Right): This shows a list of all the data, variables, and functions
you have created. It's your workspace.
4 Plots/Files/Help (Bottom Right): This is where your charts (plots) appear, where you
can find your files, and where you get help if you get stuck.
Week 1 Summary
R is a powerful language for data analysis. You write your code in RStudio, which has four
main panels: Console (for typing commands), Script Editor (for saving code), Environment
(for viewing your data), and Plots (for viewing charts).
Five Key Points to Remember
5 R is designed for statistical computing and data visualization.
6 RStudio is an IDE that makes using R much easier and more user-friendly.
7 Always install R before installing RStudio.
8 The Console executes code immediately, while the Script Editor allows you to save
your code.
9 The Environment panel keeps track of all the data objects you create.
Ten Multiple-Choice Questions
10 What is the primary purpose of the R programming language?
a) Web development
b) Statistical computing and graphics
c) Video editing
d) Game developmentAnswer: b
11 Which software acts as an Integrated Development Environment (IDE) for R?
a) Microsoft Excel
b) Python
c) RStudio
d) TableauAnswer: c
12 Where do you write code in RStudio if you want to save it for later use?
a) Console
b) Script Editor
c) Environment
d) PlotsAnswer: b
13 Which panel in RStudio shows the data and variables you have created?
a) Console
b) Script Editor
c) Environment
d) PlotsAnswer: c
14 What is the correct order of installation for R and RStudio?
a) RStudio then R
b) R then RStudio
c) They must be installed at the same time
d) It doesn't matterAnswer: b
15 Where do you see the immediate output of a command you type in RStudio?
a) Console
b) Script Editor
c) Environment
d) PlotsAnswer: a
16 Which of the following is NOT a typical application of R?
a) Predicting customer behavior
b) Analyzing patient data
c) Designing 3D models for video games
d) Tracking project impact for NGOsAnswer: c
17 In the RStudio analogy, what is R compared to?
a) The steering wheel
b) The dashboard
c) The engine
d) The tiresAnswer: c
18 Which panel in RStudio would you look at to see a bar chart you just created?
a) Console
b) Script Editor
c) Environment
d) PlotsAnswer: d
19 R is considered:
a) A spreadsheet software
b) A statistical computing environment
c) A database management system
d) A word processorAnswer: b
Five Short-Answer Questions
20 Explain the difference between R and RStudio. Model Answer: R is the
programming language that performs the calculations, while RStudio is the Integrated
Development Environment (IDE) that provides a user-friendly interface to write and
run R code.
21 Name two ways R is used in the business sector. Model Answer: R is used to
analyze sales data and predict customer behavior.
22 Describe the function of the Console panel in RStudio. Model Answer: The
Console panel is where users type commands and see the immediate results or output
of those commands.
23 Why is the Script Editor important for long-term projects? Model Answer: The
Script Editor allows users to write and save their code, so they can run it again later
without having to type it all out from scratch.
24 How might an NGO use R? Model Answer: An NGO might use R to analyze survey
data from the communities they serve to track the impact of their projects.
Three Practical Exercises
25 Install R on your computer, then install RStudio.
26 Open RStudio, type 10 + 5 in the Console, and press Enter to see the result.
27 Create a new R Script in the Script Editor, type # My First Script at the top, and save
the file as "Week1_Practice.R".
Common Mistakes Beginners Make
• Typing in the wrong place: Beginners often type code in the Script Editor and
expect it to run immediately without clicking "Run" or "Source".
• Confusing R and RStudio: Beginners sometimes think they need to open R first, but
they only need to open RStudio to work.
Connection to Next Topic
Understanding the RStudio interface (Week 1) is crucial because you will use the Script
Editor and Console constantly to write and test the basic R syntax and variables you will
learn in Week 2.
Week 2: Introduction to R (continued)
Basics of R Syntax: Variables and Data Types
What is a Variable? A variable is like a labeled box where you store data. Instead of
remembering the actual number or word, you just remember the label.
# Let's create a variable called 'age' and put the number 21 in it.
age <- 21
# Now we can use 'age' in our calculations.
print(age)
Explanation: <- is the assignment operator. It means "put the value on the right into the box
on the left."
What are Data Types? Data types tell R what kind of information is inside the box.
• Numeric: Numbers with or without decimals (e.g., 5, 3.14).
• Character: Text or strings, always wrapped in quotes (e.g., "John").
• Logical: True or False values (e.g., TRUE, FALSE).
Operators
Arithmetic Operators: Used for math.
• + (Add), - (Subtract), * (Multiply), / (Divide), ^ (Power).
Relational Operators: Used to compare things.
• == (Equal to), != (Not equal to), < (Less than), > (Greater than).
Logical Operators: Used to combine conditions.
• & (AND - both must be true), | (OR - at least one must be true), ! (NOT - reverses the
value).
Week 2 Summary
Variables are labeled boxes for storing data using the <- operator. R handles different types of
data, mainly Numeric, Character, and Logical. You use arithmetic operators for math,
relational operators to compare values, and logical operators to combine conditions.
Five Key Points to Remember
28 Use <- to assign values to variables.
29 Character data types must always be enclosed in quotes ("").
30 Numeric data types can be integers or decimals.
31 Logical operators (&, |, !) are used to evaluate multiple conditions.
32 The double equals sign == is used for comparison, while a single = or <- is used for
assignment.
Ten Multiple-Choice Questions
33 Which operator is used to assign a value to a variable in R?
a)= b) <- c) -> d) Both a and b Answer: d (Note: = works in some contexts, but <- is
the standard and safest).
34 What is the data type of the value "Hello"?
a) Numeric
b) Character
c) Logical
d) IntegerAnswer: b
35 Which of the following is a Logical operator?
a)+ b) == c) & d) / Answer: c
36 What will be the result of 5 > 3in R?
a)5 b) 3 c) TRUE d) FALSE Answer: c
37 If x <- 10 and y <- 5, what is the result of x * y?
a)15 b) 5 c) 50 d) 2 Answer: c
38 Which data type is used for True/False values?
a) Character
b) Numeric
c) Logical
d) FactorAnswer: c
39 What does the !=operator mean?
a) Equal to
b) Less than
c) Greater than
d) Not equal toAnswer: d
40 If x <- 5 and y <- 10, what is the result of x < y & y > 5?
a)TRUE b) FALSE c) 5 d) 10 Answer: a
41 Which of the following is NOT an arithmetic operator?
a)+ b) * c) ^ d) == Answer: d
42 What will x <- "5" + 5result in?
a)10 b) "55"c) An error
d)5 Answer: c (You cannot add a character to a numeric directly).
Five Short-Answer Questions
43 What is the difference between a variable and a data type? Model Answer: A
variable is a named container used to store data, while a data type describes the kind
of data stored in that container (e.g., Numeric, Character, Logical).
44 Why do we use quotes when creating a Character variable? Model Answer:
Quotes tell R that the content inside is text (a string) rather than a variable name or a
number.
45 Explain the difference between = and == in R. Model Answer: = (or <-) is used to
assign a value to a variable, while == is used to compare two values to see if they are
equal.
46 Give an example of a real-life situation where a Logical operator might be useful.
Model Answer: A school might use a Logical operator to find students who have
completed their homework AND attended class (e.g., homework_done &
attended_class).
47 What happens if you try to add a Character and a Numeric variable together?
Model Answer: R will return an error because it does not know how to perform
mathematical operations on text.
Three Practical Exercises
48 Create three variables: name (Character), score (Numeric), and passed (Logical).
49 Use arithmetic operators to calculate the average of three numbers stored in variables.
50 Write a relational statement that checks if a variable temperature is greater than 30.
Common Mistakes Beginners Make
• Forgetting quotes: Beginners often type x <- Hello instead of x <- "Hello", causing
an error.
• Confusing assignment and comparison: Beginners might write if (x = 5) instead of
if (x == 5).
Connection to Next Topic
Now that you know how to store data in variables (Week 2), Week 3 will teach you how to
write functions and use control structures to automate tasks using those variables.
Week 3: Programming Basics in R
Writing Functions
What is a Function? A function is a reusable block of code that performs a specific task.
Instead of typing the same code over and over, you write a function once and call it whenever
you need it.
# Creating a function to calculate a discount
calculate_discount <- function(price, discount_rate) {
discounted_price <- price - (price * discount_rate)
return(discounted_price)
}
# Using the function
final_price <- calculate_discount(100, 0.20) # 20% off 100
print(final_price) # Output: 80
Control Structures
Conditional Statements (if, else): These tell R to make decisions. "If this is true, do this;
otherwise, do that."
age <- 20
if (age >= 18) {
print("You are an adult.")
} else {
print("You are a minor.")
Loops (for, while): These tell R to repeat a task multiple times.
• for loop: Repeats a specific number of times.
# Print numbers 1 to 5
for (i in 1:5) {
print(i)
• while loop: Repeats as long as a condition is true.
count <- 1
while (count <= 3) {
print("Hello!")
count <- count + 1
Applying Functions (apply, lapply, sapply)
When working with lists or data frames, you don't need to write a for loop. R has built-in
"apply" functions.
• apply(): Applies a function to rows or columns of a matrix/data frame.
• lapply(): Applies a function to a list and returns a list.
• sapply(): Applies a function to a list and simplifies the result (e.g., returns a vector).
Week 3 Summary
Functions are reusable blocks of code. Control structures like if/else allow your code to make
decisions, while for and while loops allow your code to repeat tasks. The apply family of
functions provides efficient ways to apply operations across multiple data elements without
writing explicit loops.
Five Key Points to Remember
51 Functions are defined using function().
52 if/else statements control the flow of execution based on conditions.
53 for loops are used when you know exactly how many times to repeat a task.
54 while loops are used when you want to repeat a task until a condition changes.
55 lapply and sapply are used to apply functions to lists, with sapply attempting to
simplify the output.
Ten Multiple-Choice Questions
56 Which keyword is used to define a function in R?
a)def b) function c) fun d) create Answer: b
57 What is the purpose of an if/elsestatement?
a) To repeat a block of code
b) To define a function
c) To make a decision based on a condition
d) To assign a variableAnswer: c
58 Which loop is best when you know exactly how many times you want to repeat a
task?
a)whileloop
b)forloop
c)repeatloop
d)apply loop Answer: b
59 What does the return()function do inside a custom function?
a) Stops the program
b) Prints the result
c) Sends the result back to where the function was called
d) Creates a new variableAnswer: c
60 Which apply function is best suited for applying a function to a list and getting a
simplified output like a vector?
a)apply() b) lapply() c) sapply() d) tapply() Answer: c
61 If you use a whileloop, what must you ensure to prevent an infinite loop?
a) Use theforkeyword
b) Update the condition variable inside the loop
c) Usesapply d) Return a value Answer: b
62 How do you call a function named my_func with the argument 5?
a)my_func <- 5 b) my_func(5) c) call my_func(5) d) run my_func 5 Answer: b
63 In for (i in 1:5), what does irepresent?
a) The total number of loops
b) A temporary variable that holds the current number in the sequence
c) The condition for the loop
d) The output of the loopAnswer: b
64 What happens if an if condition evaluates to FALSE and there is no elseblock?
a) R throws an error
b) The code inside theifblock runs anyway
c) Theifblock is skipped, and the program continues
d) The program stopsAnswer: c
65 Which of the following is NOT part of the apply family of functions?
a)apply() b) lapply() c) sapply() d) papply() Answer: d
Five Short-Answer Questions
66 Explain the concept of a function in R using an analogy. Model Answer: A
function is like a coffee machine. You put in specific ingredients (arguments), the
machine performs a set process (the function body), and it gives you a result (return
value), like a cup of coffee.
67 When would you use a while loop instead of a for loop? Model Answer: You use a
while loop when you don't know exactly how many times the loop needs to run, but
you know the condition that should stop it (e.g., keep drawing cards from a deck until
you get an Ace).
68 What is the main advantage of using lapply or sapply over a for loop? Model
Answer: They are generally more concise, often faster, and specifically designed to
work with lists and vectors, reducing the chance of manual indexing errors.
69 How do you pass an argument to a function? Model Answer: You place the
argument value inside the parentheses when calling the function, like
my_function(argument_value).
70 Why is the return() statement important in a function? Model Answer: It specifies
the value that the function should output so it can be stored in a variable or used
elsewhere in the code.
Three Practical Exercises
71 Write a function that takes a person's age and prints whether they are a child, adult, or
senior.
72 Use a for loop to print the squares of numbers from 1 to 10.
73 Create a list of three character vectors and use sapply to find the length of each vector.
Common Mistakes Beginners Make
• Infinite loops: Forgetting to update the condition in a while loop, causing the
program to run forever.
• Scope confusion: Creating a variable inside a function and expecting it to be
available outside the function.
Connection to Next Topic
Functions and control structures (Week 3) are the building blocks of programming. In Week
4, you will learn how to structure your data into Vectors, Data Frames, and Lists so that you
can use those programming basics to analyze the data.
Week 4: Data Structures in R
Vectors
A vector is a sequence of elements of the same data type. It's like a single row or column in
Excel.
# Creating a numeric vector of ages
ages <- c(25, 30, 35, 40)
# Creating a character vector of names
names <- c("Alice", "Bob", "Charlie", "David")
Factors
Factors are used to represent categorical data. Instead of storing text, R stores numbers
(levels) behind the scenes to save memory and make analysis faster.
# Creating a factor for hospital departments
department <- factor(c("Cardiology", "Pediatrics", "Cardiology", "Oncology"))
print(department)
Matrices and Arrays
• Matrix: A 2D collection of elements of the same data type (like a grid).
# Creating a 2x3 matrix
my_matrix <- matrix(1:6, nrow=2, ncol=3)
• Array: Like a matrix, but it can have more than two dimensions (e.g., 3D).
Data Frames
A data frame is R's version of an Excel spreadsheet. It can contain different data types in
different columns. This is the most common structure you will work with.
# Creating a data frame for students
students_df <- [Link](
Name = c("Alice", "Bob", "Charlie"),
Age = c(20, 21, 22),
Grade = c("A", "B", "A")
Lists
A list is a collection of elements that can be of different data types and structures. It's like
a messy drawer where you can throw anything in.
# Creating a list with different data types
my_list <- list("A string", 10, TRUE, c(1, 2, 3))
Week 4 Summary
R uses different structures to organize data. Vectors hold 1D data of the same type. Factors
handle categorical data efficiently. Matrices are 2D grids of the same type, while Data
Frames are 2D grids allowing different types (like spreadsheets). Lists are flexible containers
for mixed data types.
Five Key Points to Remember
74 Vectors must contain elements of the same data type.
75 Data Frames are the most important structure for data analysis, similar to Excel
sheets.
76 Factors are used for categorical data and are stored internally as integers.
77 Matrices can only hold one data type, whereas Data Frames can hold multiple.
78 Lists can hold any combination of data types and structures.
Ten Multiple-Choice Questions
79 Which data structure is most similar to an Excel spreadsheet?
a) Vector
b) Matrix
c) Data Frame
d) ListAnswer: c
80 What is the key limitation of a Vector in R?
a) It can only hold 10 elements
b) It must contain elements of the same data type
c) It cannot hold numbers
d) It is 2-dimensionalAnswer: b
81 Which data structure is specifically designed to handle categorical data efficiently?
a) Vector
b) Factor
c) Matrix
d) ListAnswer: b
82 If you want to store both text and numbers in a single 2D structure, which should you
use?
a) Matrix
b) Vector
c) Data Frame
d) ArrayAnswer: c
83 What is the output of c(1, 2, 3)?
a) A list
b) A vector
c) A matrix
d) A data frameAnswer: b
84 Which data structure can hold a vector, a data frame, and a string all at once?
a) Factor
b) Matrix
c) List
d) ArrayAnswer: c
85 How does R store Factors internally to save memory?
a) As characters
b) As integers (levels)
c) As logical values
d) As double vectorsAnswer: b
86 What does the matrix()function require to create a 2x3 grid?
a)nrow=3, ncol=2 b) nrow=2, ncol=3 c) rows=2, columns=3 d) dim=2:3 Answer: b
87 Which structure is 1-dimensional?
a) Matrix
b) Data Frame
c) Vector
d) ArrayAnswer: c
88 If you try to combine a number and text in a vector, what will R do?
a) Throw an error
b) Convert the number to text (coercion)
c) Keep them separate
d) Delete the textAnswer: b
Five Short-Answer Questions
89 Explain the difference between a Matrix and a Data Frame. Model Answer: A
Matrix is a 2D structure that can only hold elements of the same data type (all
numbers or all text). A Data Frame is also 2D but can hold different data types in
different columns (e.g., a column of names and a column of ages).
90 Why would a hospital prefer to use Factors for patient departments instead of
Character vectors? Model Answer: Factors are more memory efficient and
computationally faster for statistical modeling because R stores the categories as
integers behind the scenes.
91 How would you represent a student's ID, their grades in 5 subjects, and a list of
their extracurricular activities in R? Model Answer: You would use a List, as it
allows you to store a single string (ID), a numeric vector (grades), and a character
vector (activities) all together.
92 What is the function used to combine elements into a vector? Model Answer: The
c() function.
93 If you have a column of "Yes" and "No" answers in a Data Frame, what data
type should it be? Model Answer: It should be a Factor.
Three Practical Exercises
94 Create a numeric vector of 5 numbers and calculate its sum.
95 Create a Data Frame representing a small NGO's staff with columns for Name, Role,
and Years of Experience.
96 Convert a character vector of colors (c("Red", "Blue", "Red", "Green")) into a Factor
and print it.
Common Mistakes Beginners Make
• Mixing types in vectors: Expecting c(1, "two", 3) to keep 1 as a number. R will
convert everything to text.
• Confusing Lists and Data Frames: Trying to access Data Frame columns like a List
without understanding the specific syntax ($ vs [[]]).
Connection to Next Topic
Now that you know how data is structured (Week 4), the next
logical step (Week 5) is learning how to get data from outside
sources (like CSV files) into these Data Frames so you can analyze
them.
Week 5: Data Import
Importing Data
Data rarely lives inside RStudio; it usually lives in files like CSVs or Excel sheets. You need
to bring it into R to analyze it.
Importing CSV Files: A CSV (Comma Separated Values) file is a simple text file where
columns are separated by commas. It's the most common format for sharing data.
# Reading a CSV file into a Data Frame
my_data <- [Link]("patient_records.csv")
# Viewing the first few rows
head(my_data)
Explanation: [Link]() is the function. You put the file name (with .csv) inside the quotes.
The result is saved into a variable (my_data) as a Data Frame.
Importing Excel Files: Excel files (.xlsx) are very common in business. To read them, you
need a special package called readxl.
# First, you must install and load the package
# [Link]("readxl") # Run this once
library(readxl)
# Reading the Excel file
my_excel_data <- read_excel("sales_data.xlsx")
Importing Text Files: Text files (.txt) can also be read using [Link]().
my_text_data <- [Link]("[Link]", header = TRUE, sep = "\t")
Explanation: header = TRUE means the first row contains column names. sep = "\t" means
the columns are separated by tabs (common in text files).
Week 5 Summary
To analyze data, you must first import it into R. [Link]() is used for comma-separated files.
For Excel files, you must use the readxl package and the read_excel() function. [Link]() is
used for text files, requiring you to specify separators.
Five Key Points to Remember
97 [Link]() is the standard function for importing CSV files.
98 To import Excel files, you must install and load the readxl package.
99 Imported data is typically stored as a Data Frame.
100 Always use quotes around the file name and path when importing.
101 Functions like head() and View() help you check if the data imported
correctly.
Ten Multiple-Choice Questions
102 Which function is used to read a CSV file?
a)read_excel() b) [Link]() c) import() d) read_data() Answer: b
103 What package is required to read .xlsxfiles?
a)csv b) excel c) readxl d) xlsx Answer: c
104 If you have a text file separated by tabs, which function is appropriate?
a)[Link]() b) read_excel() c) [Link]() d) [Link]() Answer: c
105 What does header = TRUEmean when reading a text file?
a) The data has no column names
b) The first row contains column names
c) The file is encrypted
d) The data is in Excel formatAnswer: b
106 Before using read_excel(), what must you do?
a) Convert the file to CSV
b) Runlibrary(readxl) c) Run [Link]("csv") d) Open Excel Answer: b
107 What is the default file format for [Link]()?
a).txt b) .xlsx c) .csv d) .doc Answer: c
108 Which function helps you view the first 6 rows of imported data?
a)tail() b) head() c) first() d) top() Answer: b
109 What data structure does [Link]()typically return?
a) Vector
b) Matrix
c) List
d) Data FrameAnswer: d
110 If your CSV file uses semicolons instead of commas, what argument should
you add to [Link]()?
a)sep = ";" b) comma = FALSE c) type = "semicolon" d) delimiter = ";" Answer: a
111 Which of the following is NOT a function for importing data?
a)[Link]() b) read_excel() c) [Link]() d) [Link]() Answer: d
Five Short-Answer Questions
112 Why do you need to use library(readxl) before importing an Excel file?
Model Answer: readxl is not a built-in base R function; it is an external package. You
must load it into your current R session using library() so R knows how to execute the
read_excel() command.
113 What is a CSV file, and why is it common in data science? Model Answer:
A CSV file is a text file where values are separated by commas. It is common because
it is simple, lightweight, and can be opened by almost any data analysis software.
114 How do you check if your data imported correctly? Model Answer: You
can use head(my_data) to see the first few rows, str(my_data) to check the data types
of the columns, or View(my_data) to open a spreadsheet-like view.
115 What is the purpose of the sep argument in [Link]()? Model Answer: It
tells R what character separates the columns in the text file (e.g., a comma, a tab \t, or
a space).
116 If R cannot find your file, what is the most likely error? Model Answer:
The file path or name is incorrect, or the file is not in the current working directory
that R is looking in.
Three Practical Exercises
117 Create a simple CSV file in Excel with three columns (Name, Age, City) and
import it into R using [Link]().
118 Download a sample .xlsx file from the internet and import it using readxl.
119 Use str() on your imported Data Frame to verify the data types of the columns.
Common Mistakes Beginners Make
• Forgetting quotes: Typing [Link](my_file.csv) instead of [Link]("my_file.csv").
• Ignoring working directories: Trying to load a file that is saved on the Desktop
when R is looking in the Documents folder.
Connection to Next Topic
Once you have imported your data (Week 5), you often need to share your findings or save
your cleaned data, which is covered in Week 6 (Data Export).
Week 6: Data Export
Exporting Data
After analyzing or cleaning data, you might want to save it to a file so you can send it to a
colleague or open it in Excel.
Writing to CSV:
# Saving the cleaned data back to a CSV file
[Link](my_data, "cleaned_patient_records.csv", [Link] = FALSE)
Explanation: [Link]() takes the Data Frame (my_data) and saves it. [Link] = FALSE
prevents R from adding a column of numbers (1, 2, 3...) on the far left, which Excel usually
doesn't need.
Writing to Excel: To write to Excel, you need the writexl package.
# [Link]("writexl")
library(writexl)
write_xlsx(my_data, "cleaned_sales_data.xlsx")
Exporting Plots
If you create a chart (which you will learn in Week 9), you can save it as an image.
# Using the pdf() function to save plots
pdf("my_plot.pdf")
plot(1:10) # This is a dummy plot
[Link]() # This tells R to stop recording and save the file
Explanation: pdf() opens a new "canvas" to draw on. plot() draws the graph. [Link]() closes
the canvas and saves the file. You can also use png() or jpeg() instead of pdf().
Week 6 Summary
Data export is the reverse of import. Use [Link]() to save Data Frames as CSV files, and
the writexl package for Excel files. You can also export visualizations using functions like
pdf() followed by [Link]() to save the generated image.
Five Key Points to Remember
120 [Link]() is the base R function for exporting data to CSV format.
121 Always use [Link] = FALSE in [Link]() to avoid extra numbering
columns.
122 The writexl package is required to export Data Frames to Excel (.xlsx).
123 Graphical exports (PDF, PNG) require opening a device (e.g., pdf()), plotting,
and closing the device ([Link]()).
124 Exported files are saved to your current working directory unless a full path is
specified.
Ten Multiple-Choice Questions
125 Which function is used to export a Data Frame to a CSV file?
a)[Link]() b) [Link]() c) [Link]() d) [Link]() Answer: c
126 What is the purpose of [Link] = FALSE in [Link]()?
a) To hide the column names
b) To prevent R from writing an extra column of row numbers
c) To save space
d) To remove missing valuesAnswer: b
127 Which package is needed to export data to an Excel file?
a)readxl b) xlsx c) writexl d) excel Answer: c
128 What function tells R to finish saving a plot to a file?
a)[Link]() b) close() c) [Link]() d) finish() Answer: c
129 If you want to save a plot as an image, which function could you use to start
the process?
a)png() b) image() c) [Link]() d) [Link]() Answer: a
130 What does [Link]()stand for?
a) Device Off
b) Deviation Off
c) Device Open File
d) Debug OffAnswer: a
131 If you do not specify a file path in [Link](), where will the file be saved?
a) The Desktop
b) The current working directory
c) The C: drive
d) The R folderAnswer: b
132 Which of the following is a valid file format for saving plots?
a).csv b) .xlsx c) .pdf d) .txt Answer: c
133 Can you use [Link]()to save a List?
a) Yes, automatically
b) No, it only works with Data Frames or Matrices
c) Only if the list has one element
d) Yes, but it will save as textAnswer: b
134 What happens if you try to export to a file name that already exists?
a) R throws an error
b) R creates a new file with a different name
c) R overwrites the existing file without warning
d) R appends the new data to the old fileAnswer: c
Five Short-Answer Questions
135 Why is [Link] = FALSE important when exporting to CSV for Excel
users? Model Answer: Excel users do not expect an unnamed column of sequential
numbers on the far left. Including it can cause issues when they try to sort or analyze
the data later.
136 Explain the three steps to save a plot in R. Model Answer: 1) Open a
graphical device (e.g., pdf("[Link]")), 2) Run the plotting command (e.g., plot(x, y)),
3) Close the device (e.g., [Link]()).
137 What is the difference between readxl and writexl? Model Answer: readxl
is used to import (read) Excel files, while writexl is used to export (write) Data
Frames to Excel files.
138 How can you change where R saves your exported CSV file? Model
Answer: You can either change your working directory using setwd() or provide the
full file path inside the [Link]() function (e.g.,
"C:/Users/Name/Documents/[Link]").
139 If you export a plot as a .pdf, what happens if you forget [Link]()? Model
Answer: R will not save the file, and the plot might appear blank or incomplete
because the "canvas" was never closed and finalized.
Three Practical Exercises
140 Take the Data Frame you created in Week 4 and export it as a CSV file named
"Practice_Data.csv".
141 Open the exported CSV file in Excel to ensure the columns and rows look
correct.
142 Write a simple code block to save a dummy plot as a .png file.
Common Mistakes Beginners Make
• Forgetting [Link](): Beginners often write the plotting code but forget to close the
device, resulting in an empty or corrupted file.
• Using readxl to write: Beginners sometimes try to use write_excel() from the readxl
package, but that package is only for reading.
Connection to Next Topic
Now that you can get data in (Week 5) and out (Week 6), Week 7 introduces the most
important tools in R for actually analyzing and cleaning that data: the tidyverse and dplyr.
Week 7: Data Manipulation
Introduction to the tidyverse Package
What is tidyverse? The tidyverse is a collection of R packages designed specifically for data
science. It makes code easier to read and write. The most important package inside it is dplyr
(for manipulating data) and ggplot2 (for visualization).
# [Link]("tidyverse")
library(tidyverse)
Working with dplyr
dplyr provides a "grammar of data manipulation". It uses intuitive verbs to change your Data
Frame.
The Pipe Operator (%>% or |>): This is the most important concept in tidyverse. It means
"and then". It takes the output of one function and passes it as the input to the next.
my_data %>% filter(Age > 30) %>% select(Name)
Translation: Take my_data, AND THEN filter for rows where Age > 30, AND THEN select
only the Name column.
Filtering (filter): Choose specific rows based on conditions.
# Keep only patients in the Cardiology department
cardiology_patients <- hospital_data %>%
filter(Department == "Cardiology")
Selecting (select): Choose specific columns to keep.
# Keep only Name and Age columns
simple_data <- hospital_data %>%
select(Name, Age)
Mutating (mutate): Create new columns or modify existing ones.
# Create a new column for Total Cost
cost_data <- hospital_data %>%
mutate(Total_Cost = Procedure_Cost + Room_Cost)
Week 7 Summary
The tidyverse is a suite of data science packages. The dplyr package provides intuitive verbs
for data manipulation: filter() for rows, select() for columns, and mutate() to create new
columns. The pipe operator (%>% or |>) chains these commands together for readable code.
Five Key Points to Remember
143 tidyverse is a collection of packages; dplyr is specifically for data
manipulation.
144 The pipe (%>%) passes data from one function to the next, reading like a
sentence.
145 filter() is used to subset rows based on logical conditions.
146 select() is used to keep only specific columns.
147 mutate() is used to create or modify columns based on existing data.
Ten Multiple-Choice Questions
148 What is the primary purpose of the tidyverse?
a) Web scraping
b) Data science and visualization
c) Game development
d) Text editingAnswer: b
149 Which package is specifically used for data manipulation in the tidyverse?
a)ggplot2 b) readxl c) dplyr d) stringr Answer: c
150 What does the pipe operator %>%do?
a) Compares two values
b) Passes the output of the left side as the first argument to the right side
c) Creates a new variable
d) Ends a line of codeAnswer: b
151 Which function is used to select specific rows from a Data Frame?
a)select() b) filter() c) mutate() d) arrange() Answer: b
152 Which function is used to choose specific columns?
a)select() b) filter() c) mutate() d) slice() Answer: a
153 How do you create a new column called Profit?
a)my_data <- Profit b) mutate(my_data, Profit = Revenue - Cost) c) filter(Profit =
Revenue - Cost) d) select(Profit = Revenue - Cost) Answer: b
154 In dplyr, what is the difference between filter() and select()?
a)filter() works on columns, select()works on rows
b)filter() works on rows, select()works on columns
c) Both work on rows
d) Both work on columnsAnswer: b
155 What happens if you chain multiple commands using %>%?
a) Only the last command runs
b) R processes them sequentially, modifying the data step by step
c) R runs them all at the same time
d) It causes an errorAnswer: b
156 If you want to keep rows where Score >= 50, which code is correct?
a)filter(data, Score >= 50) b) select(data, Score >= 50) c) mutate(data, Score >= 50)
d) arrange(data, Score >= 50) Answer: a
157 Which of the following is NOT a core dplyrverb?
a)filter b) select c) mutate d) import Answer: d
Five Short-Answer Questions
158 Explain the pipe operator (%>%) using an everyday analogy. Model
Answer: The pipe is like an assembly line in a factory. The raw material (data) goes
through the first machine (e.g., filter), the output of that machine goes into the second
machine (e.g., select), and so on.
159 When would you use mutate() instead of base R assignment? Model
Answer: mutate() is cleaner and easier to read, especially when creating multiple new
columns at once or when used in a pipeline with other dplyr functions.
160 How does select() help in data analysis? Model Answer: It reduces the size
of the dataset by removing unnecessary columns, making it easier to read, process,
and visualize specific variables.
161 Can you use multiple conditions in a filter() function? Model Answer: Yes,
you can use logical operators like & (AND) and | (OR) inside filter() to apply multiple
conditions (e.g., filter(Age > 30 & Age < 50)).
162 What is the difference between filter() and slice()? Model Answer: filter()
selects rows based on the values within the data (e.g., Age > 30), while slice() selects
rows based on their position or row number (e.g., the first 10 rows).
Three Practical Exercises
163 Load the dplyr package and use a built-in dataset (like mtcars).
164 Use filter() to find all cars with more than 6 cylinders.
165 Use %>% to filter the data and then select() only the mpg and cyl columns.
Common Mistakes Beginners Make
• Forgetting the pipe: Beginners often write filter(my_data, x > 5) and try to pipe it
incorrectly, or they nest functions deeply instead of using %>%.
• Confusing filter and select: Beginners sometimes use filter(Name == "Alice") when
they mean select(Name).
Connection to Next Topic
After filtering, selecting, and creating new columns (Week 7),
Week 8 will teach you how to group this data together and
summarize it, as well as how to reshape it using tidyr.
Week 8: Data Manipulation (continued)
Grouping and Summarizing Data
Often, you don't just want to look at raw data; you want summaries (like averages or totals).
• group_by(): Groups the data by a specific column (e.g., group by Department).
• summarise(): Calculates summary statistics for each group.
library(dplyr)
# Calculate average age for each department
hospital_summary <- hospital_data %>%
group_by(Department) %>%
summarise(Average_Age = mean(Age, [Link] = TRUE),
Total_Patients = n())
Explanation: [Link] = TRUE tells R to ignore missing values when calculating the mean. n()
counts the number of rows in each group.
Working with tidyr: Reshaping Data
Sometimes data is in the wrong shape for analysis.
• Wide data: Many columns (e.g., Jan, Feb, Mar sales).
• Long data: Many rows (e.g., a Month column with values like Jan, Feb, Mar).
Pivoting (pivot_longer): Turning wide data into long data.
library(tidyr)
# Combining multiple month columns into one 'Month' column and one 'Sales'
column
long_data <- wide_data %>%
pivot_longer(cols = c(Jan, Feb, Mar),
names_to = "Month",
values_to = "Sales")
Unpivoting (pivot_wider): Turning long data into wide data.
# Spreading 'Month' and 'Sales' back into separate columns
wide_data <- long_data %>%
pivot_wider(names_from = "Month",
values_from = "Sales")
Handling Missing Data
Missing data (represented as NA in R) is very common.
• Finding missing data: [Link](my_data)
• Removing missing data: drop_na(my_data)
• Replacing missing data: replace_na(my_data, 0) (replaces NAs with 0).
Week 8 Summary
The dplyr functions group_by() and summarise() allow you to calculate statistics for specific
categories. The tidyr package handles reshaping data: pivot_longer() makes data taller (fewer
columns, more rows), and pivot_wider() makes data wider (more columns, fewer rows).
Missing data (NA) can be removed or replaced.
Five Key Points to Remember
166 summarise() is almost always used after group_by().
167 pivot_longer() takes column names and puts them into a single new column.
168 pivot_wider() takes values from a column and spreads them into new columns.
169 Missing data in R is represented by NA.
170 The [Link] = TRUE argument is essential when calculating means or sums to
avoid getting NA as a result.
Ten Multiple-Choice Questions
171 Which function is used to split data into groups?
a)summarise() b) group_by() c) arrange() d) mutate() Answer: b
172 What does summarise()do?
a) Creates a new column
b) Filters rows
c) Calculates summary statistics for groups
d) Reshapes dataAnswer: c
173 If your data has many columns for different months, what shape is it?
a) Long
b) Wide
c) Tall
d) DeepAnswer: b
174 Which function converts wide data to long data?
a)pivot_wider() b) pivot_longer() c) gather() d) spread() Answer: b
175 What argument tells mean()to ignore missing values?
a)ignore_na = TRUE b) remove = TRUE c) [Link] = TRUE d) [Link] = TRUE
Answer: c
176 What symbol represents missing data in R?
a)NULL b) NA c) "" d) 0 Answer: b
177 Which function removes all rows containing NA?
a)remove_na() b) drop_na() c) filter_na() d) delete_na() Answer: b
178 In pivot_longer(), what does names_tospecify?
a) The new column name for the values
b) The new column name for the old column names
c) The columns to be deleted
d) The data frame nameAnswer: b
179 Which function checks if a value is missing?
a)[Link]() b) [Link]() c) [Link]() d) [Link]() Answer: c
180 If you use summarise() without group_by(), what happens?
a) It throws an error
b) It calculates the statistic for the entire dataset as a single group
c) It ignores the summarise command
d) It returns the raw dataAnswer: b
Five Short-Answer Questions
181 Explain the difference between pivot_longer() and pivot_wider(). Model
Answer: pivot_longer() takes multiple columns and stacks them into a single column
(making the data frame longer). pivot_wider() takes values from a single column and
spreads them out into multiple new columns (making the data frame wider).
182 Why is it important to use [Link] = TRUE in summary functions like
mean()? Model Answer: If you do not use [Link] = TRUE, and there is even one
missing value in the column, the entire calculation will return NA (missing), ruining
your summary.
183 How would you find out how many missing values are in a specific
column? Model Answer: You can use sum([Link](my_data$column_name)). [Link]()
returns TRUE for missing values, and sum() counts the TRUEs.
184 What is the benefit of converting wide data to long data? Model Answer:
Long data is generally easier to plot with ggplot2 and easier to group and summarize
because the grouping variable is in a single column rather than spread across many
column headers.
185 Can you use summarise() to calculate multiple statistics at once? Model
Answer: Yes, you can separate multiple calculations with commas (e.g.,
summarise(Average = mean(x), Total = sum(x))).
Three Practical Exercises
186 Use group_by() and summarise() on the mtcars dataset to find the average
mpg for each number of cylinders (cyl).
187 Create a wide data frame with columns Jan, Feb, Mar and use pivot_longer()
to combine them.
188 Create a vector with some NA values and use mean() with and without [Link]
= TRUE to see the difference.
Common Mistakes Beginners Make
• Forgetting group_by(): Beginners sometimes just use summarise() and wonder why
they get a single row of output instead of a row for each category.
• Confusing names_to and values_to: In pivot_longer(), it's easy to mix up which
column gets the old names and which gets the actual data values.
Connection to Next Topic
Now that your data is clean and summarized (Weeks 7-8), Week 9 will teach you how to turn
those numbers into beautiful visualizations using ggplot2.
Week 9: Data Visualization
Overview of Visualization in R
Visualizing data helps you see patterns, trends, and outliers that are hard to spot in a raw Data
Frame. R has two main ways to make plots: Base R (built-in) and ggplot2 (part of tidyverse).
Using Base R Graphics
Base R is simple and quick for checking data, but the plots are not very pretty.
# A simple scatterplot
plot(x = my_data$Height, y = my_data$Weight)
Introduction to ggplot2
ggplot2 is the industry standard for data visualization in R. It uses a "layered" grammar. The
basic structure:
189 ggplot(data, aes(x, y)): Sets up the canvas and maps data to axes.
190 geom_point(), geom_line(), etc.: Adds the actual shapes (geometries).
library(ggplot2)
# Creating a scatterplot
ggplot(data = my_data, aes(x = Height, y = Weight)) +
geom_point()
Explanation: aes() stands for "aesthetics". It tells ggplot2 which variables to put on the x and
y axes. geom_point() adds the dots.
Common Geometries:
• geom_point(): Scatterplots (for two numeric variables).
• geom_line(): Line graphs (for trends over time).
• geom_bar(): Bar charts (for categorical counts).
• geom_histogram(): Histograms (for the distribution of a single numeric variable).
Customizing Plots
You can make plots look professional using labs(), theme(), and color arguments.
ggplot(data = my_data, aes(x = Height, y = Weight, color = Gender)) +
geom_point() +
labs(title = "Height vs Weight by Gender",
x = "Height (cm)",
y = "Weight (kg)") +
theme_minimal() # Changes the background and grid lines
Week 9 Summary
Visualization is crucial for understanding data. While Base R has basic plotting functions,
ggplot2 is the preferred tool. ggplot2 builds plots in layers: ggplot() sets the data and axes
(aes), and geom_*() functions add the visual elements (points, lines, bars). You can
customize plots with labs() for labels and theme() for styling.
Five Key Points to Remember
191 ggplot2 builds plots layer by layer using the + sign.
192 aes() maps your data variables to visual properties like x-axis, y-axis, or color.
193 geom_point() is for scatterplots, geom_bar() is for bar charts.
194 labs() is used to add titles and change axis labels.
195 theme_minimal() is a quick way to make a plot look clean and modern.
Ten Multiple-Choice Questions
196 Which package is the industry standard for data visualization in R?
a)dplyr b) readxl c) ggplot2 d) base Answer: c
197 In ggplot2, what does aes()stand for?
a) Aesthetics
b) Assign
c) Axis
d) AssessmentAnswer: a
198 Which function adds dots to a scatterplot?
a)geom_bar() b) geom_line() c) geom_point() d) geom_scatter() Answer: c
199 How are layers added in a ggplotcommand?
a) Using a comma, b) Using the plus sign + c) Using the pipe %>% d) Using a
semicolon ; Answer: b
200 Which geometry is best for showing the distribution of a single numeric
variable?
a)geom_point() b) geom_line() c) geom_bar() d) geom_histogram() Answer: d
201 Which function is used to change the title of a plot?
a)theme() b) labs() c) title() d) names() Answer: b
202 If you want to color points based on a categorical variable, where do you put
the variable?
a) Insideggplot() b) Inside aes() c) Inside geom_point() d) Inside labs() Answer: b
203 What does theme_minimal()do?
a) Makes the plot black and white
b) Removes the grid lines and changes the background
c) Makes the plot smaller
d) Removes the data pointsAnswer: b
204 Which plot type is best for showing trends over time?
a) Scatterplot
b) Histogram
c) Line graph
d) Pie chartAnswer: c
205 What happens if you forget the + sign between layers in ggplot2?
a) The plot is created but ugly
b) R throws an error
c) The layers are ignored
d) The data is deletedAnswer: b
Five Short-Answer Questions
206 Explain the "layered grammar" of ggplot2. Model Answer: It means you
start with a blank canvas (ggplot()) defining the data and axes, and then you add
layers on top of it (like geom_point() or geom_bar()) using the + sign to build the
final chart.
207 When would you use a histogram instead of a bar chart? Model Answer:
Use a histogram for a continuous numeric variable (like height or age) to see its
distribution. Use a bar chart for categorical data (like car brands or departments) to
see counts or averages.
208 Why is it important to put variables inside aes()? Model Answer: Putting
variables inside aes() tells ggplot2 to map that data to the visual property (like the x-
axis or color), allowing R to automatically generate legends and scale the axes
correctly.
209 How do you change the x-axis label to "Income (USD)"? Model Answer:
Add + labs(x = "Income (USD)") to the end of the ggplot code.
210 What is the main difference between Base R plots and ggplot2 plots?
Model Answer: Base R plots are quick and functional but look basic. ggplot2 plots
require more code but are highly customizable, follow a logical grammar, and look
much more professional.
Three Practical Exercises
211 Load ggplot2 and create a scatterplot using the mtcars dataset (mpg on x, hp
on y).
212 Add a title and change the x-axis label to "Miles Per Gallon".
213 Add theme_minimal() to the plot to see how the style changes.
Common Mistakes Beginners Make
• Forgetting the + sign: Putting a comma instead of a plus sign between ggplot() and
geom_point().
• Putting variables outside aes(): Typing geom_point(x = mpg) instead of aes(x =
mpg), which breaks the plot.
Connection to Next Topic
Once you know the basics of ggplot2 (Week 9), Week 10 will show you how to create
advanced, multi-panel visualizations and interactive charts.
Week 10: Advanced Visualizations
Faceting
Faceting allows you to split one plot into multiple small plots based on a categorical variable.
It's like looking at the data through different windows.
ggplot(data = my_data, aes(x = Height, y = Weight)) +
geom_point() +
facet_wrap(~ Department)
Explanation: facet_wrap(~ Department) creates a separate scatterplot for each unique value
in the Department column.
Combining Multiple Plots
Sometimes you want to put different types of plots side-by-side. The patchwork package
makes this easy.
library(patchwork)
# Create two plots
plot1 <- ggplot(data, aes(x, y)) + geom_point()
plot2 <- ggplot(data, aes(x)) + geom_histogram()
# Combine them side by side
plot1 + plot2
Creating Interactive Visualizations with plotly
Static plots (PDF/PNG) are great for reports, but interactive plots are great for websites or
presentations. The plotly package converts ggplot2 charts into interactive HTML widgets.
library(plotly)
# Convert a static ggplot to interactive
my_interactive_plot <- ggplot(data, aes(x, y, color = Group)) + geom_point()
ggplotly(my_interactive_plot)
Explanation: When you hover over the points in the resulting plot, you will see tooltips with
the exact data values.
Week 10 Summary
Advanced visualization includes facet_wrap() to split data into subplots, patchwork to
combine different plots into a single image, and plotly (specifically ggplotly()) to make static
ggplot2 charts interactive for web use.
Five Key Points to Remember
214 facet_wrap() is used to create a grid of plots based on a categorical variable.
215 The tilde ~ symbol is required inside facet_wrap().
216 The patchwork package uses the + sign to combine multiple ggplot objects.
217 plotly is a package used to make charts interactive (zoomable, hoverable).
218 ggplotly() is the specific function that converts a ggplot object into a plotly
object.
Ten Multiple-Choice Questions
219 Which function is used to split a plot into multiple panels based on a variable?
a)split_plot() b) facet_wrap() c) panel_wrap() d) group_plot() Answer: b
220 What symbol is used before the variable name in facet_wrap()?
a)@ b) $ c) ~ d) # Answer: c
221 Which package is commonly used to combine multiple plots side-by-side?
a)ggplot2 b) dplyr c) patchwork d) plotly Answer: c
222 How do you combine plot1 and plot2 using patchwork?
a)c(plot1, plot2) b) plot1 + plot2 c) plot1 %>% plot2 d) combine(plot1, plot2)
Answer: b
223 What package is used to create interactive visualizations?
a)interactive b) shiny c) plotly d) webgl Answer: c
224 Which function converts a ggplot object to a plotlyobject?
a)ggplotly() b) plotly() c) convert_plot() d) make_interactive() Answer: a
225 What is a major benefit of using plotly?
a) It prints faster
b) It allows users to hover over data points to see values
c) It saves as a PDF
d) It uses less memoryAnswer: b
226 If you want to facet by two variables (rows and columns), which function do
you use?
a)facet_wrap() b) facet_grid() c) split_grid() d) panel_grid() Answer: b
227 Can you use patchworkto combine a plot and a text annotation?
a) Yes, usingplot_annotation()b) No, only plots
c) Only if the text is a plot
d) Yes, usingtext_add() Answer: a
228 What happens when you run ggplotly()in RStudio?
a) A PDF opens
b) An interactive viewer pane opens
c) The console prints text
d) Nothing happensAnswer: b
Five Short-Answer Questions
229 Explain what faceting does to a dataset. Model Answer: Faceting takes a
single dataset and splits it into subsets based on the levels of a categorical variable,
drawing a separate plot for each subset.
230 Why is the tilde (~) used in facet_wrap(~ Department)? Model Answer:
The tilde is the formula operator in R. It tells the function "use the variable on the
right side of the tilde to determine the groups."
231 What is the advantage of using patchwork over manually arranging plots
in Word or PowerPoint? Model Answer: patchwork keeps the plots as code,
meaning if the data changes, you can re-run the code and the combined layout will
automatically update without manual resizing or copy-pasting.
232 How does plotly handle the aesthetics (colors, sizes) defined in ggplot2?
Model Answer: plotly (via ggplotly()) automatically translates the ggplot2 aesthetics
into interactive features, such as coloring the legend and providing hover tooltips with
the mapped data.
233 If you want to save an interactive plotly chart, what format should you
use? Model Answer: You should save it as an HTML file, as interactivity requires
web technologies (JavaScript) to function.
Three Practical Exercises
234 Create a scatterplot using ggplot2 and add facet_wrap(~ cyl) using the mtcars
dataset.
235 Create two different plots and use patchwork to arrange them in a 2x1 grid
(one on top of the other).
236 Take one of your ggplot2 charts and wrap it in ggplotly() to see it become
interactive.
Common Mistakes Beginners Make
• Forgetting the + in patchwork: Beginners sometimes try to use %>% instead of +
when combining plots with patchwork.
• Faceting on continuous variables: Trying to facet on a numeric variable without
converting it to a factor first, which creates a separate plot for every single number.
Connection to Next Topic
After mastering advanced static and interactive plots (Week 10),
Weeks 11 and 12 will apply these visualization skills to specific
types of data: Time Series and Text Data.
Week 11-12: Time Series and Text Data
Time Series Analysis
Time series data is data collected over time (e.g., daily stock prices, monthly sales).
Handling Date and Time Objects (lubridate): R needs to know that a column is a date, not
just text. The lubridate package makes this easy.
library(lubridate)
# Converting text to dates
my_date <- ymd("2023-10-25") # Year-Month-Day
my_time <- ymd_hms("2023-10-25 14:30:00") # Year-Month-Day
Hour:Minute:Second
Explanation: ymd() tells R the text is in Year-Month-Day format.
Plotting Time Series Data: When plotting time series, you usually put the Date on the x-axis
and a numeric variable on the y-axis using geom_line().
ggplot(data = sales_data, aes(x = Date, y = Revenue)) +
geom_line()
Text Data Processing
Text data (like customer reviews or tweets) requires cleaning before analysis.
String Manipulation (stringr): The stringr package makes working with text easier.
library(stringr)
my_text <- " Hello World! "
# Remove extra spaces
clean_text <- str_trim(my_text)
# Convert to lowercase
lower_text <- str_to_lower(clean_text)
# Check if text contains a word
has_hello <- str_detect(lower_text, "hello")
Basics of Text Mining: Text mining involves turning text into numbers so you can count
word frequencies.
# Using tidytext (part of tidyverse ecosystem)
library(tidytext)
# Splitting text into individual words (tokenization)
words <- my_reviews %>%
unnest_tokens(word, review_text)
Week 11-12 Summary
Time series data requires proper date formatting, which lubridate handles using functions like
ymd(). Time series are best visualized using line graphs (geom_line()). Text data is cleaned
using stringr (e.g., str_trim(), str_to_lower()) and prepared for analysis using tokenization
(splitting sentences into words).
Five Key Points to Remember
237 Dates in R should be converted using lubridate functions like ymd() or mdy().
238 Time series plots almost always use geom_line() with Date on the x-axis.
239 stringr provides consistent functions for text manipulation (all start with str_).
240 str_trim() removes leading and trailing spaces from text.
241 Tokenization (e.g., unnest_tokens()) is the first step in text mining to break
text into analyzable units (words).
Ten Multiple-Choice Questions
242 Which package is best for handling dates in R?
a)stringr b) lubridate c) dplyr d) ggplot2 Answer: b
243 What function converts a "Year-Month-Day" string to a Date object?
a)date() b) ymd() c) mdy() d) [Link]() Answer: b
244 Which geometry is most appropriate for plotting time series data?
a)geom_point() b) geom_bar() c) geom_line() d) geom_histogram() Answer: c
245 Which package is used for string manipulation?
a)stringr b) textR c) lubridate d) stringi Answer: a
246 What does str_trim()do?
a) Converts text to lowercase
b) Removes extra spaces at the beginning and end of a string
c) Joins two strings together
d) Counts the characters in a stringAnswer: b
247 Which function converts all characters in a string to lowercase?
a)str_lower() b) str_to_lower() c) lower_case() d) str_down() Answer: b
248 What is the first step in basic text mining called?
a) Summarization
b) Filtering
c) Tokenization
d) FacetingAnswer: c
249 What does tokenization do?
a) Removes punctuation
b) Splits text into smaller units like words
c) Translates text
d) Encrypts textAnswer: b
250 If your date string is "10-25-2023", which lubridatefunction should you use?
a)ymd() b) dmy() c) mdy() d) ydm() Answer: c
251 Which function checks if a string contains a specific pattern?
a)str_find() b) str_detect() c) str_search() d) str_match() Answer: b
Five Short-Answer Questions
252 Why is it important to convert text dates into Date objects using
lubridate? Model Answer: Converting text to Date objects allows R to understand the
chronological order of the data, enabling you to calculate time differences, filter by
date ranges, and plot time series correctly.
253 Explain the concept of tokenization in text mining. Model Answer:
Tokenization is the process of breaking down large chunks of text (like paragraphs or
sentences) into smaller, meaningful units (tokens), usually individual words, so they
can be counted and analyzed.
254 How does str_trim() help in data cleaning? Model Answer: str_trim()
removes accidental leading or trailing spaces (e.g., " Apple" becomes "Apple"), which
prevents R from treating the same word as two different categories due to hidden
spaces.
255 Why do we use line graphs instead of scatterplots for time series data?
Model Answer: Line graphs connect the data points in chronological order, making it
much easier to visualize trends, seasonality, and changes over time compared to
disconnected scatterplot points.
256 What is the difference between ymd() and mdy()? Model Answer: ymd()
expects the date string to be formatted as Year-Month-Day, while mdy() expects
Month-Day-Year. Using the wrong one will result in incorrect dates or errors.
Three Practical Exercises
257 Use lubridate to convert the string "2023-12-25" into a Date object.
258 Create a simple line graph showing a trend over 5 days using ggplot2.
259 Use stringr to convert a messy string with extra spaces and uppercase letters
into a clean, lowercase string.
Common Mistakes Beginners Make
• Plotting dates as characters: Forgetting to use lubridate, resulting in a plot where the
x-axis treats dates as unordered text categories rather than a continuous timeline.
• Using the wrong lubridate function: Using ymd() on a "Day-Month-Year" string,
which causes R to misinterpret the date.
Connection to End of Course
By mastering time series and text data, you have now covered the full spectrum of data types
(numeric, categorical, dates, and text) and the core tidyverse workflow for data science in R.
Quick-Reference Cheat Sheet
This cheat sheet summarizes the most important commands and functions covered in the
course. Keep this handy during your exam!
1. R Basics & Syntax
Command Description
<- or = Assignment operator (e.g., x <- 5)
# Comment (R ignores this line)
print(x) Prints the value of x
class(x) Shows the data type of x
2. Data Structures
Function Description
c() Combine elements into a Vector
matrix() Create a Matrix (2D, same data type)
[Link]() Create a Data Frame (2D, mixed data types)
list() Create a List (mixed types and structures)
factor() Convert vector to a Factor (categorical)
3. Data Import/Export
Function Description
[Link]("[Link]") Import a CSV file
readxl::read_excel("[Link]") Import an Excel file
[Link](df, "[Link]", [Link] = FALSE) Export Data Frame to CSV
writexl::write_xlsx(df, "[Link]") Export Data Frame to Excel
4. Data Manipulation (dplyr & tidyr)
Function Description
%>% or |> Pipe operator (passes data to the next function)
filter() Select rows based on conditions
select() Select specific columns
mutate() Create or modify columns
group_by() Group data by a categorical variable
summarise() Calculate summary statistics
pivot_longer() Reshape wide data to long data
pivot_wider() Reshape long data to wide data
drop_na() Remove rows with missing values (NA)
5. Data Visualization (ggplot2)
Function Description
ggplot(data, aes(x, y)) Initialize plot and map aesthetics
geom_point() Add scatterplot points
geom_line() Add line graph
Function Description
geom_bar() Add bar chart
geom_histogram() Add histogram
labs() Add titles and axis labels
theme_minimal() Apply a clean theme to the plot
facet_wrap(~ var) Split plot into subplots
plotly::ggplotly() Make a ggplot interactive
6. Specialized Data (Time & Text)
Function Description
lubridate::ymd() Convert text to Date (Year-Month-Day)
lubridate::mdy() Convert text to Date (Month-Day-Year)
stringr::str_trim() Remove leading/trailing spaces
stringr::str_to_lower() Convert text to lowercase
stringr::str_detect() Check if text contains a pattern
tidytext::unnest_tokens() Tokenize text into words