0% found this document useful (0 votes)
2 views156 pages

Statistical computing II Note

The document outlines a course on Statistical Computing II focusing on R programming, detailing its objectives, installation, and interface, including R Studio. It introduces R as a powerful tool for data analysis and visualization, emphasizing its open-source nature and user-friendly features. The course aims to equip students with the skills to explore, visualize, and analyze data using R, culminating in the ability to run basic models.

Uploaded by

eyobabeje888
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)
2 views156 pages

Statistical computing II Note

The document outlines a course on Statistical Computing II focusing on R programming, detailing its objectives, installation, and interface, including R Studio. It introduces R as a powerful tool for data analysis and visualization, emphasizing its open-source nature and user-friendly features. The course aims to equip students with the skills to explore, visualize, and analyze data using R, culminating in the ability to run basic models.

Uploaded by

eyobabeje888
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

Statistical Computing II (R, SAS)

Department of Statistics
Bahir Dar-Ethiopia

Dereje Tesfaye Zike (Assistant Professor of Statistics), BDU


derejetesfaye11@[Link]
+251-910533558

March, 2026

2/8/2026
Learning Objectives

The objective of this course:

• Familiarize with the basics of R.


• Develop proficiency in R programming (explore, visualize, analyze data) &
• Run basic models using R

At the end of the course, you will be able to:

Familiarity with R
Explore, visualize, analyze data &
Run basic models in R

2/8/2026
1 Introduction to

2/8/2026
1.1 Introduction

R is programming language for data analytics and scientific research.


Originally created and developed by Ross Ihaka & Robert Gentleman in 1996 &
currently maintained by international R-core development team.

R can be used both as a programming language and as a software package which


researchers can use to manage, manipulate, analyze and visualize data.
What is the advantages of using R?
✓ R is open source and freely available documents.
✓ R can producing publication quality figures.
✓ R has freely available ‘packages’ for special or unusual analyses.

2/8/2026
1.1 Introduction
• Download & Installing R
To get up and running the first thing, you need to do is install R.
R can be downloaded as a self-extracting file from the Comprehensive R Archive Network
(CRAN) at [Link] or [Link]

2
4. Now, the link allows 1
downloading an installer
3
extension (.exe) file.

5. Run the .exe file & step


through the installation wizard
accepting
2/8/2026
the default settings.
1.1 Introduction
• The R Interface
In Windows, once you have started R you will see the standard graphical user interface (GUI).
Menu Bar
Tool Bar

The GUI contains a limited number of menu like:


✓ File - load script, load/save session (workspace) or command history/change Directory
✓ Edit - Cut/Paste/GUI preferences
✓ View- used to view or hide the toolbar/statusbar
✓ Misc - stop computations/ list/remove objects in session
✓ Packages - allows one to install new/update packages
✓ Help - An essential resource!
and a tool bar where you can access commonly used commands

R console window
command line prompt

2/8/2026
1.1 Introduction
• The R Interface
In addition, a graphics window will appear automatically when using any plotting function.

Graphics window

2/8/2026
1.1 Introduction
• The R Interface
In addition, an interactive text editor window will create from file→ new script

Write small bits of code here and run it, but you
should saved by ctrl+S b/c it is temporary & usually
unsaved.

Output appears here.

Don't worry too much about the R GUI, you won't be using it much as you will be using R Studio
instead
2/8/2026
1.1 Introduction
• R Studio
R Studio can be thought of as an add-on to R which provides a more user-friendly interface,
incorporating the R Console, a script editor and other useful functionality.
This is because, the R command difficult when things start to get a little bit more complex.
Once R is installed, you can then proceed to the installation of R Studio from the
[Link]

3
4. Now, the link allows
downloading an installer
extension (.exe) file. 1
5. Run the .exe file & step
through the installation
2
wizard accepting the
default settings.
2/8/2026
1.1 Introduction
• R Studio Interface/Orientation
When you open R studio for the first time you should see the following layout.

Environment/History/Connections window

Console window
The Console is the workhorse of R.
Files/Plots/Packages/Help/Viewer window
This is where R evaluates all the code you write.
You can type R code directly into the Console at the
command line prompt (>).

2/8/2026
1.1 Introduction
• R Studio Interface/Orientation
However, once you start writing more R code this becomes rather bulky & it is better to create an R
script. To create a new R script:

Source pane

The new window is a script editor & where you will


write your code.

2/8/2026
1.1 Introduction
• R Studio Interface/Orientation
To run your code from your script editor simply place your cursor on the line of code or select & then
click on the ‘Run’ button, then the result is found in the console window.

click

You can save your R scripts as a .R file by selecting the ‘File’


ctrl + enter
menu and clicking on save/save as… as any other files.

2/8/2026
1.1 Introduction
• R Studio Interface/Orientation
The Environment / History / Connections/tutorial window shows you lots of useful information.
You can access each component by clicking on the appropriate tab in the pane.

The ‘Tutorial’ tab provides setp-by-step guidance and examples to help you.

The ‘Connections’ tab allows you to connect to various data sources from external databases.

The ‘History’ tab contains a list of all the commands you have entered into the R Console.

The ‘Environment’ tab displays all the objects you have created in the current (global) environment.
These objects can be things like data you have imported or functions you have written.
There’s also an ‘Import Dataset’ button which will import data saved in a variety of file formats.

2/8/2026
1.1 Introduction
• R Studio Interface/Orientation
The Files/Plots/Packages/Help/Viewer window shows you lots of useful information.
You can access each component by clicking on the appropriate tab in the pane.

The ‘Presentation’ pane create, preview, & deliver presentations directly from your R environment.

The ‘Viewer’ tab displays local web content such as web graphics generated by some packages.

The ‘Help’ tab displays the R help documentation for any function.

The ‘Packages’ tab lists all of the packages that you have installed on your computer.
You can also install new packages and update existing packages by clicking on the ‘Install’ and ‘Update’
buttons respectively.

The ‘Plots’ tab is where all the plots you create in R are displayed (unless you tell R otherwise).
You can zoom, export (jpeg, png, pdf…), and scroll back through previously created plots.

The ‘Files’ tab lists all external files and directories in the current working directory on your computer.

2/8/2026
1.1 Introduction
• R Packages
The base installation of R comes with many useful packages as standard, but
complex tasks may require intensive coding using base packages functions.
Packages extensions that contain code, data, & documentation in a standardized format that can be
installed and used by users of R to solve specific analytical problems.
Therefore, packages can be downloaded from the CRAN website which currently hosts over 21145
packages used for various purposes.

To install a package from CRAN : install. packages(“name of the package”) Or

from packages pane as:

Once you have installed a package


onto your computer,
it is need to load the package by
using the library() function to use.

2/8/2026
1.1 Introduction
• R Packages
R packages are sometimes updated to improve or modify functionality.
You can update your installed R packages in RStudio by clicking:

2/8/2026
1.1 Introduction
• Introduction to R markdown
What is R markdown?
a simple and easy to use plain text language used to combine your R/studio code,

results from your data analysis (including plots and tables) and written scripts into a single nicely
formatted and reproducible document.

How you create an R markdown document?

If your R/R studio is not resent install library(rmarkdown).

Click on the toolbar + (File→ New File) → R Markdown... then in the pop-up window, give the
document a 'Title' and enter the 'Author'.
3

4
1
Once you have created, it's good practice to save this
file somewhere convenient by File → Save as… in R
studio.

2 5
2/8/2026
1.1 Introduction
• Introduction to R markdown
The file extension of your new R markdown file is .Rmd.

Each R markdown document is composed of 3 main components,

• a YAML header: includes the title, author and date

• formatted text: a text paragraph that contains all of the text formatting that you are likely to need &

• one or more code chunks: the heart of the matter to include R code into your R markdown
document.

To include R code into your R markdown doc you simply place your code into a 'code chunk‘ from the:

Menu bar Tool bar


1
1
2
2

You can write the script here & click on to run the code.

2/8/2026
1.1 Introduction
• Introduction to R markdown
Now, to convert your .Rmd file to a HTML/ pdf/word document click on the little black triangle next to
the Knit icon at the top of the source window and select knit to HTML/pdf/word.

If everything went smoothly a new file will have been created and saved in the same directory as your
.Rmd file created.
When we run the code chunk both the R code and the resulting output are displayed in the final
document.

2/8/2026
➢ Markdown is simple plain text, that is styled using special characters, including:
➢ # : a header element
➢ **: bold text.
➢ *: italic text
➢ ` : code blocks.

2/8/2026
1.2 Getting started with R (R studio)

2/8/2026
1.2 Getting started with R/studio
• Some R basics
Before we continue, here are a few things to bear in mind as you work through this section.

R/studio is:
case sensitive i.e. A is not the same as a and anova is not the same as Anova.

Commands are separated either by a semi-colon (‘;’), or by a newline.

Comments can be put almost anywhere, starting with a hash mark (‘#’), everything to the end of the
line is a comment.

2/8/2026
1.2 Getting started with R/studio
• Objects in R
You will do in R is the concept that everything is an object.
These objects can be almost anything, from
• a single number or character string (like a word) to highly complex structures like the output of a
plot,
• a summary of your statistical analysis or a set of R commands that perform a specific task.
Understanding how you create objects and assign values to objects is key to understanding R.
To create an object we simply give the object a name.
We can then assign a value to this object using the assignment operator as <- (a ‘less than’
symbol & a hyphen) or equal to (=) or ->.

Example:
To view the value of the object you simply type the name of the object.
object
value

2/8/2026
1.2 Getting started with R/studio
• Objects in R
Now, R knows all about it and will keep track of it during this current R session. Therefore,
all of the objects you create will be stored in the current R session &
you can view all the objects in your workspace in RStudio by clicking on the ‘Environment’.

If you want to see the characteristics, click on the down arrow on the ‘List’ icon in the same
pane and change to ‘Grid’

2/8/2026
1.2 Getting started with R/studio
• Objects in R
There are many different types of values that you can assign to an object.
An object may also contain many values (a vector).
These can be assigned in a number of different ways.
One simple method is to use the function, c, which is short form concatenate (literally to
link or join together).

Example

2/8/2026
1.2 Getting started with R/studio
• Naming objects
Ideally your object names should be kept both short and informative which is not always
easy.
If you need to create objects with multiple words, use either an underscore / a dot
between words/ capitalize the different words.
An object name cannot start with a number or a dot followed by a number &
does not blanks, and special characters (%, $, !, #, and @) .
In addition, make sure you don’t name your objects with reserved words (i.e. TRUE, NA).
Example: the following codes generate errors

2/8/2026
1.2 Getting started with R/studio
• Vector arithmetic and using functions in R
Vectors can be manipulated using the same functions described above.

However, you must be careful when adding or subtracting vectors of different lengths.
Example:

2/8/2026
1.2 Getting started with R/studio
• Vector arithmetic and using functions in R
Up until now you have been creating simple objects by directly assigning a single value to an object.
The base installation of R comes with many functions already defined or
you can increase the power of R by installing packages.
The first function we will learn about is the c() function.

When you use a function in R:


First, the function name is always followed by a pair of round brackets
Secondly, the argument(s) of a function are placed inside the round brackets & are
separated by commas.
Some typical functions used with vectors include mean(), var(), sd(), range(), length(), max(), min(),
summary().

Example:

2/8/2026
1.2 Getting started with R/studio
• Positional index
To extract elements based on their position we simply write the position inside the [ ].
Note that the positional index starts at 1 rather than 0.
For example, to extract the 3rd value of my_vec.

We can also extract more than one value by using the c() function inside the square
brackets. Here we extract the 1st, 5th, 6th and 8th element from the my_vec object.

Or we can extract a range of values using the : notation.


For example, to extract the values from the 3rd to the 8th elements.

2/8/2026
1.2 Getting started with R/studio
• Logical index
Another useful way to extract data from a vector is to use a logical expression as an index.
For example, to extract all elements with a value greater than 4 in the vector my_vec .

R will only extract those elements that satisfy this logical condition.
If we look at the output of just the logical expression without the square brackets you can
see that R returns a vector containing either TRUE or FALSE which correspond to whether
the logical condition is satisfied for each element.

2/8/2026
1.2 Getting started with R/studio
• Logical index
We can also combine multiple logical expressions.
In R the & symbol means AND and the | symbol means OR.
For example, to extract values in my_vec which are less than 6 AND greater than 2.

• Replacing elements
We can change the values of some elements in a vector using our [ ] notation in
combination with the assignment operator (<-).
For example, to replace the 4th value of our my_vec object from 6 to 500.

2/8/2026
1.2 Getting started with R/studio
• Ordering elements
In addition to extracting particular elements from a vector we can also order the values contained in a
vector.
To sort the values from lowest to highest value we can use the sort() function.

To reverse the sort, from highest to lowest, we can either include the decreasing = TRUE
argument when using the sort() function.

2/8/2026
1.2 Getting started with R/studio
• Ordering elements
It is also, first sort the vector using the sort() function and then reverse the sorted vector using the rev()
function.
This is an example of nesting one function inside another function.

2/8/2026
1.2 Getting started with R/studio
• Ordering elements
Now let we sort one vector according to the values of another vector.
To do this we should use the order() function in combination with [ ].
For example, let we want to sort a vector height containing the height of 5 different people &
another vector called [Link] containing the names of these people.
To order the people in [Link] in ascending order of their height.

2/8/2026
1.2 Getting started with R/studio
• R Help
To access R’s built-in help facility to get information on any function simply use the help() function.
For example, to open the help page for the mean() function:
help("mean") OR ?mean OR [Link] (“mean”) OR ??mean
After you run the code, the help page is displayed in the ‘Help’ tab in the Files pane like:

2/8/2026
1.2. Data structures in R

2/8/2026
1.2.0 Introduction
In chapter one you have created simple data in R as a vector, but

you will have much more complicated datasets from various experiments & surveys.

Hence, in this chapter you will learn:


✓how R deals with different types of data & data structures,
✓how to import your data into R, and
✓how to explore and summarize your data.

2/8/2026
1.2.1 Data Types
Understanding the different types of data and how R deals with these data is important.
Hence, R has basic types of data like; numeric, integer, logical, character and complex.

• Numeric data are numbers that contain a decimal. Actually they can also be whole
numbers.
• Integers are whole numbers (those numbers without a decimal point).

• Logical data take on the value of either TRUE or FALSE. There’s also another special type
of logical called NA to represent missing values.
• Character data are used to represent string values. A special type of character string is a
factor, which is a string but with additional attributes (like levels or an order).
• Complex data is a number that can be expressed in the form a + bi, where a & b are real
numbers, and i is the imaginary unit (where i² = -1).

2/8/2026
1.2.1 Data Types
R is able to automatically distinguish between different classes of data by their nature.
You can find out the type (or class) of any object using the class() function.

Example:

Alternatively, you can ask if an object is a specific class using a logical test.
The is.[classOfData]() family of functions will return either a TRUE or a FALSE.

Example:

2/8/2026
1.2.1 Data Types
It can sometimes be useful to be able to change the class of a variable using the
as.[className]() family of coercion functions.

Example:

Here is a summary table of some of the logical test and coercion functions available.

Type Logical Test Coercing


Chatacter [Link] [Link]
Numeric [Link] [Link]
Logical [Link] [Link]
Factor [Link] [Link]
Complex [Link] [Link]

2/8/2026
1.2.2 Data Structures
Perhaps the simplest type of data structure is the vector.
Vectors that have a single value (length 1) are called scalars.
Vectors can contain numbers, characters, factors or logicals, but not mixtures of these
types of data.

Scalar
Vector
Note that:
you can include NA (remember this is special type of logical) to denote missing data in
vectors with other data types.

Example:

2/8/2026
1.2.2 Data Structures
Another useful data structure used in many disciplines is the matrix.
A matrix is simply a vector that has additional attributes called dimensions.
Arrays are just multidimensional matrices.
Again, matrices and arrays must contain elements all of the same data class.

matrix

Array

2/8/2026
1.2.2 Data Structures
A convenient way to create a matrix or an array is to use the matrix() and array() functions
respectively.
Example: create a matrix from a sequence 1 to 16 in four rows.

When using the array() function we define the dimensions using the dim = argument
Example: Consider the above example and create an array with 2 rows, 4 columns in 2
different matrices.

2/8/2026
1.2.2 Data Structures
Sometimes it is also useful to define row and column names for your matrix.
To do this use the rownames() and colnames() functions.
Example: consider the above matrix dataset and give row name as A, B, C & D and column
name as a, b, c, & d.

2/8/2026
1.2.2 Data Structures
Once you have created your matrices you can perform matrix operations by using built in
functions.
For example to:
✓ transpose a matrix we use the transposition function t().
✓ extract the diagonal elements of a matrix and store them as a vector we can use the
diag() function.

The usual matrix addition, multiplication etc can be performed.


✓ perform matrix addition we use + operator
✓ perform matrix multiplication we use %*% operator

2/8/2026
1.2.3 lists
Whilst vectors and matrices are constrained to contain data of the same type, lists are able
to store mixtures of data types.
This makes for a very flexible data structure which is ideal for storing irregular or non-
rectangular data.
Thus, a list is an ordered collection of objects that can be of different modes (e.g. numeric
vector, array, etc.).
To create a list we can use the list() function.

output

2/8/2026
1.2.4 Data Frames
By far the most commonly used data structure to store data is the data frame.
A data frame is a powerful two-dimensional object made up of rows and columns.
In a data frame rows referring to observations/ measurements & columns referring to
variables
We can construct a data frame using the [Link]() function.
Example: create three vectors [Link], [Link] and [Link] and include all of these
vectors in a data frame object called dataf.

2/8/2026
1.2.4 Data Frames
By far the most commonly used data structure to store data in is the data frame.
A data frame is a powerful two-dimensional object made up of rows and columns which is very similar
to a matrix.
Typically, in a data frame each row corresponds to an individual observation & each column
corresponds to a different measured or recorded variable.
We can construct a data frame using the [Link]() function.
Example: create three vectors [Link], [Link] and [Link] and include all of these vectors in a data
frame object called dataf.

We can check the dimensions of the data frame object using the dim() function.
A useful function is str() which will return a compact summary of the structure of the data frame.
Strings are automatically converted to factors using the stringsAsFactors = TRUE function.
Practically a table is a data frame that contains variables (columns) and row (cases/individuals)
[Link]
2/8/2026
1.2.5 Importing data
The most common approach is to create a data frame by importing from an external file.
To do this, you will need to have your data correctly formatted and saved in a file format
that R is able to recognize.
Fortunately, R is able to recognize a wide variety of file formats, although in reality you will
using only two or three.
Once you have saved your data file in a suitable format you can now read this file into R
using the read. “ ”() function (table, csv, csv2, delim)
You can even import data from spreadsheet files or other statistics software directly into R
by install packages.
Thus, we can import data from:
• SPSS, STATA & SAS with package `haven`
• Excel with package `readxl`
• Text with package `readr`
2/8/2026
1.2.6 Data exploration
Now that you are able to successfully import your data from an external file into R.
Next, working with data is a fundamental skill and R is good at data management,
summarizing and visualizing data.
Let we import the flowers data and remind ourselves of the structure of it.

[Link] Data management


• Selecting variables in the dataframe
To access the data in any of the variables (columns) in our data frame we can use the $
notation.
For example, to access the height variable in our flowers data frame we can use
flowers$height and this will return a vector of the height data.

2/8/2026
1.2.6. Data management
• Positional indexes
To use positional indexes we simple have to write the position of the rows and columns
we want to extract inside the [ ].
For example, to extract the:

2/8/2026
1.2.6 Data management
• Logical indexes
We can also extract data from our data frame by using all of the logical operators.
For example, to extract the:

2/8/2026
1.2.6 Data management
• Logical indexes
An alternative method of selecting parts of a data frame based on a logical expression is
to use the subset() function instead of the [ ].
Advantage of using subset() → no longer need to use the $ notation when specifying
variables inside the data frame.
Disadvantage is that subset() is less flexible than the [ ] notation.

For example, let we extract sub dataset that contains only treatment=tip, nitrogen =
medium and block=2.

2/8/2026
1.2.6 Data management
• Ordering data frames
Remember when we used the function order() to order one vector based on the order of
another vector.
This comes in very handy if you want to reorder rows in your data frame.
For example:

2/8/2026
1.2.6. Data management
• Ordering data frames
If we wanted to do the same thing with a factor (or character) variable, we would need to
use the function xtfrm() inside our order() function.
For example, we want to order the data frame by variable nitrogen as follows:

When ordering character variables, R automatically sorts them alphabetically, but you
might prefer to arrange them based on the levels of a factor.
To achieve this, you can use the factor() function to define the desired order of the levels.
Example:

2/8/2026
1.2.6 Data management
• Adding columns and rows
Sometimes it is useful to be able to add extra rows and columns of data to our data frames.

To append additional rows to an existing data frame we can use the rbind() function & to
append columns the cbind() function.

Example: to append the rows


NewDataName <- rbind(data1, data2)
Example: to append the columns
NewDataName <- cbind(data1, data2)

2/8/2026
1.2.6 Data management
• Merging data frames
Instead of just appending either rows or columns to a data frame we can also merge two or
more data frames together using the merge () function.
Notice that to merge two or more data frames, we need one common columns or indices
(mostly ID).

Example:

2/8/2026
1.2.6 Data management
• Reshaping data frames
Reshaping data into different formats is a common task.
There are two main data frame shapes that you will come across:
✓ the ‘long’ format (sometimes called stacked) &
✓ the ‘wide’ format.
There are many ways to convert between these two formats but we use the:
✓ melt() function to convert from wide to long formats &
✓ dcast() function to convert from a long to a wide format data frame from the reshape2
package.
Example: consider the following Diabetes data measured from four patients in three
different times including variable sex.

2/8/2026
1.2.6 Data management
• Reshaping data frames
To convert from wide to long formats data frame the:

✓ [Link] = c("ID", "sex") argument is a vector of the variables you want to stack,
✓ [Link] = c("DM0", "DM1", "DM2") argument identifies the columns of the
measurements in different conditions,
✓ [Link] = “time" argument specifies what you want to call the stacked column
of your different times in your output data frame and
✓ [Link] = “Diabetes" is the name of the column of your stacked measurements in
your output data frame.
2/8/2026
1.2.6 Data management
• Reshaping data frames
To convert from a long format to a wide format data frame the:

✓ ID + sex bit of the formula means that we want to keep these columns separate,
✓ ~ condition part is the column that contains the labels that we want to split into new
columns in our new data frame, &
✓ [Link] = “Diabetes" argument is the column that contains the measured data.

2/8/2026
2.7 Summarizing Data
Another really useful function for summarising data is the aggregate() function.
The aggregate() function works in a very similar way to tapply() but is a bit more flexible.
For example, to calculate the mean of the variables height, weight, leafarea and shootarea
for each level of nitrogen we can write the code:

flowers[, 4:7] specifies the columns we want to summarise in the flowers data
by = argument specifies a list of factors

FUN= argument names the function to apply (mean in this example).

We can also use the aggregate() function in a different way by using the formula method .
For example:

2/8/2026
2.1. Conditional Execution
In R, conditional execution is achieved using the if statement. The if statement
allows you to execute a block of code only if a specified condition is TRUE. You
can also use else and else if to handle additional conditions.

Syntax Examples
Example 1:
If statement
if (condition) { x <- 10
# code to execute if condition is TRUE if (x > 5) {
}
print("x is greater than 5")
}
Example 2:
x <- 10
if (x > 5) {
print(x =x^2)
2/8/2026 }
2.1. Conditional Execution
Syntax Examples
Example 1:

2.1.1. if Statement: x <- 3


if (x > 5) {

if (condition) { print("x is large")

# code if condition is TRUE } else {

} else { print("x is small")

# code if condition is FALSE }

} Example 2:
x <- 3
if (x > 5) {
print(x =sqrt(x))
} else {
print(x = x^2)
2/8/2026 }
2.1. Conditional Execution
Syntax Examples
else if for Multiple Conditions: Example 1:

If (condition1) { x <- 0

# code for condition1 if (x > 0) {

} else if (condition2) { print("Positive")

# code for condition2 } else if (x < 0) {

} else { print("Negative")

# default code } else {

} print("Zero")
}

2/8/2026
2.1. Conditional Execution
Syntax Examples
Example 1:
➢ Vectorized ifelse() Function: Use
x <- c(1, -2, 3)
ifelse() to apply conditions element-
result <- ifelse(x > 0, "Positive", "Not positive")
wise to vectors: result
# Output: "Positive" "Not positive" "Positive"

2/8/2026
2.1.1. Repetitive Execution
Syntax Examples
➢ Repetitive Execution: Loops execute code Example 1:
repeatedly based on a sequence or condition. for (i in 5:10) {
print(i)
➢ for Loop: Iterates over a sequence (vector, list,
# Prints 5, 6, 7, 8, 9, 10
etc.):
}
for (value in sequence) {
# code to repeat
}

2/8/2026
2.1.1. Repetitive Execution
Syntax Examples
Example 1:
➢ while Loop: Runs while a condition is
count <- 1
TRUE:
while (count <= 5) {
while (condition) {
print(count)
# code to repeat
count <- count + 1 # Prevents infinite loops
}
}

2/8/2026
2.1.1. Repetitive Execution
Syntax Examples
Example 1:
➢ repeat Loop with break: Runs
count <- 1
indefinitely until break is called:
repeat {
repeat {
print(count)
# code
count <- count + 1
if (condition) break
if (count > 5) break
}
}

2/8/2026
2.1.1. Repetitive Execution
Syntax Examples
Control Statements Example (skip even numbers):

➢ break: Exits the loop immediately. for (i in 1:10) {

➢ next: Skips to the next iteration. if (i %% 2 == 0) next

Key Notes print(i) # Prints 1, 3, 5, 7, 9

➢ Vectorization: Avoid loops when possible using }


vectorized operations (e.g., ifelse(), apply()
functions).
➢ Syntax: Always use == for comparisons (not =).
➢ Infinite Loops: Ensure while loops have an exit
condition.
➢ Readability: Indent code within braces for clarity

2/8/2026
2.1.1. Repetitive Execution
Example: Combine Conditions and Loops: Check if numbers in a vector are positive or negative:

numbers <- c(-2, 5, 0, 9)


for (n in numbers) {
if (n > 0) {
print(paste(n, "is positive"))
} else if (n < 0) {
print(paste(n, "is negative"))
} else {
print(paste(n, "is zero"))
}
}

2/8/2026
2.2-2.4 R - Functions
➢ A function is a set of statements organized together to perform a specific task.

➢ Functions are created using the function() directive and are stored as R objects just like
anything else.

➢ In particular, they are R objects of class “function”.

➢ R has a large number of in-built functions and the user can create their own functions.

➢ In R, a function is an object so the R interpreter is able to pass control to the function,


along with arguments that may be necessary for the function to accomplish the actions.

➢ The function in turn performs its task and returns control to the interpreter as well as any
result which may be stored in other objects.

➢ Function Definition: An R function is created by using the keyword function.

➢ The basic syntax of an R function definition is as follows :


function_name <- function(arg_1, arg_2, ...) {
Function body
2/8/2026
}
2.2-2.4 R - Functions
➢ Arguments: Information can be passed into functions as arguments.
➢ Arguments are specified after the function name, inside the parentheses.
➢ You can add as many arguments as you want, just separate them with a comma.
➢ The following example has a function with one argument (arg_1)
function_name <- function(arg_1{
Function body
}
➢ The following example has a function with more than one arguments (arg_1, arg_2, ...)
function_name <- function(arg_1, arg_2, ...) {
Function body
}
Example 1: function with 1 argument (fname). Example 2: The following function expects 2
my_function<-function(fname) { arguments, and gets 2 arguments (fname, lname)
paste(fname, "Stat 3rd year") my_function <- function(fname, lname) {
} paste(fname, lname)
my_function("Tsegaye") }
my_function(“Gezahegn") my_function("Dereje", "Tesfaye")
my_function("Biruk")

2/8/2026
2.2-2.4 R - Functions
Function Components

➢ The different parts of a function are :


❖ Function Name: This is the actual name of the function. It is stored in R environment as an object with this
name.

❖ Arguments: An argument is a placeholder. When a function is invoked, you pass a


value to the argument. Arguments are optional; that is, a function may contain no
arguments. Also arguments can have default values.

❖ Function Body : The function body contains a collection of statements that defines
what the function does.

❖ Return Value: The return value of a function is the last expression in the function
body to be evaluated.
➢ R has many in-built functions which can be directly called in the program without defining them first.

➢ We can also create and use our own functions referred as user defined functions

2/8/2026
2.2-2.4 R - Functions
Built-in Function
➢ Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc.

➢ They are directly called by user written programs.

print(seq(10,20)) # Create a sequence of numbers from 10 to 20.

print(mean(25:82)) # Find mean of numbers from 25 to 82

print(sum(41:68)) # Find sum of numbers from 41 to 68


2.2-2.4 R - Functions
User-defined Function
➢ We can create user-defined functions in R.
➢ They are specific to what a user wants and once created they can be used like the built-in functions.
➢ Below is an example of how a function is created and used.
# Create a function to print squares of numbers in sequence.
[Link] <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Calling a Function
# Create a function to print squares of numbers in sequence.
[Link] <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function [Link] supplying 6 as an argument.
[Link](6)
2.2-2.4 R - Functions
User-defined Function
➢ We can create user-defined functions in R.
Calling a Function without an Argument
# Create a function without an argument.
[Link] <- function() {
for(i in 1:5) {
print(i^2)
}
}
# Call the function without supplying an argument.
[Link]()
2.2-2.4 R - Functions
User-defined Function
➢ Calling a Function with Argument Values (by position and by name)

➢ The arguments to a function call can be supplied in the same sequence as defined in the function or
they can be supplied in a different sequence but assigned to the names of the arguments.
# Create a function with arguments.
[Link] <- function(a,b,c) {
result <- a * b + c
print(result)
}
# Call the function by position of arguments.
[Link](5,3,11)
# Call the function by names of the arguments.
[Link](a = 11, b = 5, c = 3)
2.2-2.4 R - Functions
User-defined Function
Calling a Function with Default Argument
➢ We can define the value of the arguments in the function definition and call the function
without supplying any argument to get the default result.
➢ But we can also call such functions by supplying new values of the argument and get non
default result.
# Create a function with arguments.
[Link] <- function(a = 3, b = 6) {
result <- a * b
print(result)
}
# Call the function without giving any argument.
[Link]()
# Call the function with giving new values of the argument.
[Link](9,5)
2.2-2.4 R - Functions
User-defined Function
Lazy Evaluation of Function
➢ Arguments to functions are evaluated lazily, which means so they are evaluated only when
needed by the function body.
# Create a function with arguments.
[Link] <- function(a, b) {
print(a^2)
print(a)
print(b)
}
[Link](6) # Evaluate the function without supplying one of the arguments
[Link](6,4) # Evaluate the function with supplying two of the arguments
2.5. Debugging functions
➢ Debugging is a process of cleaning a program code from bugs to run it successfully.

➢ While writing codes, some mistakes or problems automatically appears after the
compilation of code and are harder to diagnose.

➢ So, fixing it takes a lot of time and after multiple levels of calls.

➢ Debugging in R is through warnings, messages, and errors.

➢ Debugging in R means debugging functions. Various debugging functions are:


❖ Editor breakpoint

❖ traceback()

❖ browser()

❖ recover()

❖ Editor Breakpoints
2.5. Debugging functions
➢ Editor Breakpoints can be added in RStudio by clicking to the left of the line in RStudio or
pressing Shift+F9 with the cursor on your line.

➢ A breakpoint is same as browser() but it doesn’t involve changing codes.

➢ Breakpoints are denoted by a red circle on the left side, indicating that debug mode will be
entered at this line after the source is run.

traceback() Function

➢ The traceback() function is used to give all the information on how your function arrived at
an error.

➢ It will display all the functions called before the error arrived called the “call stack” in
many languages, R favors calling traceback.
2.5. Debugging functions
Example:
➢ traceback() function displays the error during
# Function 1
evaluations.
function_1 <- function(a){
➢ The call stack is read from the function that was
a+5
run(at the bottom) to the function that was running(at
}
the top).
# Function 2
➢ Also we can use traceback() as an error handler which
function_2 <- function(b) {
will display error immediately without calling of
traceback. function_1(b)

# Calling function

function_2("s")

# Call traceback()

traceback()
2.5. Debugging functions
➢ traceback() function displays the error during Example:
evaluations. # Function 1
➢ The call stack is read from the function that was function_1 <- function(a){
run(at the bottom) to the function that was running(at a+5
the top).
}
➢ Also we can use traceback() as an error handler which
# Function 2
will display error immediately without calling of
function_2 <- function(b){
traceback.
function_1(b)

# Calling error handler

options(error = traceback)

function_2("s")
2.5. Debugging functions
➢ browser() Function: browser() function is inserted into # Function 1
functions to open R interactive debugger. function_1 <- function(a){
➢ It will stop the execution of function() and you can browser()
examine the function with the environment of itself. a+5
➢ In debug mode, we can modify objects, look at the }
objects in the current environment, and also continue
# Function 2
executing.
function_2 <- function(b) {
➢ Also, debug() statement automatically inserts
function_1(b)
browser() statement at the beginning of the function.
}

function_2("s")
2.5. Debugging functions
➢ recover() Function: recover() statement is used as an # Function 1
error handler and not like the direct statement. options(error = recover)
➢ In recover(), R prints the whole call stack and lets you function_1 <- function(a){
select which function browser you would like to enter. browser()
➢ Then debugging session starts at the selected location. a+5

# Function 2

function_2 <- function(b) {

function_1(b)

function_2("s")
3. Probability and Sampling Distributions
➢ A probability/random sample is a sample ➢ Random Variable: a random variable is a
real-valued variable that gets its value
selected such that each item or person in
from a random experiment
the population being studied has a known
OR
likelihood of being included in the sample
➢ a random variable X is a function from
➢ A probability is a measure of the likelihood
the sample space to the real numbers.
that an event in the future will happen. It
➢ a random variable is a real-valued
can only assume a value between 0 and 1
function that assigns a numerical value to
each possible outcome of the random
experiment.
3. Probability and Sampling Distributions
Discrete Random Variable Continuous Random Variable
➢ Discrete Random Variable: a random ➢ Continuous Random Variable:
variable X is called discrete, if X takes A random variable X is
on a finite or countable infinite number continuous r.v. if X takes all
of values. values in an interval on the real
➢ Probability Mass Function (pmf): All the line
information about a discrete r.v. can be ➢ Probability density function
summed up in a function called the
(pdf): a function with values f(x),
probability function/probability mass
defined over the set of all real
function (pmf).
numbers, is pdf of the continuous
➢ Thus, if X is a discrete r.v. then its pmf is
random variable X.
defined as p(X) = p(X = x).

2/8/2026
3. Probability and Sampling Distributions

Discrete Distribution Continuous Distribution


✓ Uniform Distribution
➢ Discrete Uniform distribution ✓ Normal (Gaussian) Distribution
✓ Bernoulli Distribution ✓ Exponential Distribution
✓ Gamma Distribution
✓ Binomial distribution ✓ Beta Distribution
✓ Hypergeometric distribution ✓ Chi-squared Distribution
✓ Cauchy Distribution
✓ Poisson distribution ✓ Weibull Distribution
✓ Negative Binomial (Pascal) distribution ✓ The t-Distribution
✓ F-distibution
✓ Geometric distribution

2/8/2026
3. R as a set of statistical tables
➢ The R suite of programs provides a simple way for statistical tables of just
about any probability distribution of interest and also allows for easy plotting of
the form of these distribution

General syntax for distribution functions

➢ There are four basic R commands that apply to the various distributions defined in
R.

➢ Letting DIST denotes the particular distribution and parameters the parameters to
specify that particular distribution
❖ d DIST(x, parameters)--- probability density of DIST evaluated at x

❖ p DIST(x, parameters)- returns Pr(DIST(parameters)<=x)

❖ q DIST(p, parameters)-- returns x satisfying Pr(DIST(parameters)<=x)=p

❖ rDIST(n, parameters)- generates a random variables from DIST(parameters)


Distribution Parameters R Function
Binomial size, prob binom
Poison lambda pois
Geometric prob geom
Negative binomial size, prob nbinom
Normal mean , sd norm
Student t df t
Chi- square df chisq
F df1,df2 f
Exponential rate exp
Gamma Shape, rate gamma
Uniform min , max unif
3.2. Built in discrete probability distributions

3.2.1. Binomial Distribution

➢ The binomial distribution model deals with finding the probability of success of an
event which has only two possible outcomes in a series of experiments.

➢ For example, tossing of a coin always gives a head or a tail.

➢ The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times
is estimated during the binomial distribution.

➢ R has four in-built functions to generate binomial distribution.


3.2.1. Binomial Distribution
Built in: function Binomial Distribution Description of the parameters used
➢ x is a vector of numbers.
❖ dbinom(x, size, prob)
➢ p is a vector of probabilities.
❖ pbinom(x, size, prob)
➢ n is number of observations.
❖ qbinom(p, size, prob) ➢ size is the number of trials.

❖ rbinom(n, size, prob) ➢ prob is the probability of success of


each trial.

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution
❖ dbinom(x, size, prob): This function gives the probability density distribution at each point

x <- seq(0,50,by = 1) # Create a sample of 50 numbers which are incremented by 1.

y <- dbinom(x,50,0.5) # Create the binomial distribution.

png(file = "[Link]") # Give the chart file a name.

plot(x, y) # Plot the graph for this sample.

[Link]() # Save the file

❖ pbinom(): This function gives the cumulative probability of an event. It is a single value
representing the probability.

x <- pbinom(26,51,0.5) # Probability of getting 26 or less heads from a 51 tosses of a coin.

print(x)

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution
❖ qbinom(): This function takes the probability value and gives a number whose cumulative
value matches the probability value.

x <- qbinom(0.25,51,1/2) # How many heads will have a probability of 0.25 will come out
when a coin. # is tossed 51 times.

print(x)

❖ rbinom(): This function generates required number of random values of given probability
from a given sample.

x <- rbinom(8,150,.4) # Find 8 random values from a sample of 150 with probability of 0.4.

print(x)

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution (Plotting the Binomial Distribution)
Visualize the PMF or CDF of the binomial distribution.

❖ PMF Plot
# Parameters

n <- 10 # Number of trials

p <- 0.5 # Probability of success

# Create a vector of possible successes (0 to n)

x <- 0:n

# Compute PMF values

pmf_values <- dbinom(x, size = n, prob = p)

# Plot the PMF

barplot(pmf_values, [Link] = x, col = "lightblue", main = "Binomial PMF (n = 10, p = 0.5)", xlab
= "Number of Successes", ylab = "Probability")

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution (Plotting the Binomial Distribution)
Visualize the CDF of the binomial distribution.

❖ CDF Plot

# Compute CDF values

cdf_values <- pbinom(x, size = n, prob = p)

# Plot the CDF

plot(x, cdf_values, type = "s", col = "blue", lwd = 2, main = "Binomial CDF (n = 10, p =
0.5)", xlab = "Number of Successes", ylab = "Cumulative Probability")

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution (Plotting the Binomial Distribution)
Comparing Binomial Distributions: Compare binomial distributions with different probabilities or sample sizes.

# Parameters

n <- 10 # Number of trials

p1 <- 0.3 # Probability of success (1)

p2 <- 0.7 # Probability of success (2)

# Create a vector of possible successes (0 to n)

x <- 0:n

# Compute PMF values for both distributions

pmf_values1 <- dbinom(x, size = n, prob = p1)

pmf_values2 <- dbinom(x, size = n, prob = p2)

# Plot the PMFs

barplot(rbind(pmf_values1, pmf_values2), beside = TRUE, col = c("lightblue", "lightgreen"), [Link] = x, main =


"Binomial PMF Comparison", xlab = "Number of Successes", ylab = "Probability")

legend("topright", legend = c("p = 0.3", "p = 0.7"), fill = c("lightblue", "lightgreen"))


3.2.2. Geometric Distribution
Built in function: Geometric Distribution

❖ in R the geometric distribution is the number of failures before a


success, not the number of trials including the success.

❖ dgeom(x, prob)
❖ pgeom(q, prob) ❖ d => density/mass function
❖ qgeom(p, prob) ❖ p => probability (cumulative distribution function) P(X <= x)
❖ q => quantiles, given q, the smallest x such that P(X <= x) > q
❖ rgeom(n, prob) ❖ r => random number generation

2/8/2026
3.2.2. Geometric Distribution
Built in function: Geometric Distribution

➢ The geometric distribution is a probability distribution that models


the number of trials needed to get the first success in a series of
independent Bernoulli trials, where each trial has the same probability
of success, p

2/8/2026
3.2.2. Geometric Distribution
Built in function: Geometric Distribution
❖ In R, you can work with the geometric distribution using the following functions:

❖ dgeom(x, prob): Probability mass function (PMF): calculates the probability of getting the
first success on the xth trial.

✓ Example: Calculate the probability of getting the first success on the 5th trial with p=0.8

dgeom(4, prob = 0.8) # Note: x is the number of failures before the first success

❖ pgeom(q, prob): Cumulative distribution function (CDF): calculates the probability


of getting the first success on or before the qth trial
✓ Example: Calculate the probability of getting the first success on or before the 5th trial
with p=0.8

pgeom(4, prob = 0.8) # Note: q is the number of failures before the first success

2/8/2026
3.2.2. Geometric Distribution
Built in function: Geometric Distribution
qgeom(p, prob): Quantile function: calculates the smallest number of trials x such that the
probability of getting the first success on or before the xth trial is at least p

❖ Example: Find the smallest number of trials x such that the probability of getting the first
success on or before the xth trial is at least 0.5, with p=0.8:

qgeom(0.5, prob = 0.8)

❖ rgeom(n, prob): Random number generation - generates n random values from the
geometric distribution.

❖ Example: Generate 10 random values from a geometric distribution with p=0.8

rgeom(10, prob = 0.8)


➢ In R, the geometric distribution is defined as the number of failures before the first success.

➢ So, if you want the number of trials until the first success, you need to add 1 to the result.

rgeom(10, prob = 0.8)+1

2/8/2026
3.2.3. Negative Binomial Distribution
Built in function: Negative Binomial Distribution
❖ The negative binomial distribution is a discrete probability distribution that models the
number of trials needed to achieve a specified number of successes in a series of independent
Bernoulli trials, where each trial has the same probability of success, p

❖ In R, you can work with the negative binomial distribution using the following functions:

❖ dnbinom(x, size, prob): Probability mass function (PMF): calculates the probability of
getting exactly x failures before achieving size successes.

❖ pnbinom(q, size, prob): Cumulative distribution function (CDF): calculates the probability
of getting q or fewer failures before achieving size successes.

❖ qnbinom(p, size, prob): Quantile function: calculates the smallest number of failures x such
that the probability of getting x or fewer failures before achieving size successes is at least p.

❖ rnbinom(n, size, prob): Random number generation: generates n random values from the
negative binomial distribution.

2/8/2026
.
3.2.3 Negative Binomial Distribution

functions Parameters
➢ dnbinom(x, size, prob): Probability mass function ➢ x or q: Number of failures.
(PMF): calculates the probability of getting exactly
x failures before achieving size successes. ➢ size: Number of successes.
➢ pnbinom(q, size, prob): Cumulative distribution
➢ prob: Probability of success on
function (CDF): calculates the probability of
getting q or fewer failures before achieving size each trial (p).
successes.
➢ p: Probability (for quantile
➢ qnbinom(p, size, prob): Quantile function:
calculates the smallest number of failures x such function).
that the probability of getting x or fewer failures
before achieving size successes is at least p. ➢ n: Number of random values to
➢ rnbinom(n, size, prob): Random number generate.
generation: generates n random values from the
negative binomial distribution.

2/8/2026
.
3.2.3 Negative Binomial Distribution
Examples
➢ dnbinom(5, size = 3, prob = 0.8) # Calculate the probability of getting exactly 5 failures
before achieving 3 successes, with p=0.8
➢ pnbinom(5, size = 3, prob = 0.8) # Calculate the probability of getting 5 or fewer failures
before achieving 3 successes, with p=0.8
➢ qnbinom(0.5, size = 3, prob = 0.2) # Find the smallest number of failures x such that the
probability of getting x or fewer failures before achieving 3 successes is at least 0.5,
with p=0.8
➢ rnbinom(10, size = 3, prob = 0.2) # Generate 10 random values from a negative binomial
distribution with 3 successes and p=0.8:

2/8/2026
3.2.3. Poisson Distribution
Built in function: Poisson Distribution
❖ The Poisson distribution is a discrete probability distribution that models the number of
events occurring in a fixed interval of time or space, given a constant mean rate of
occurrence (λ).

❖ It is often used for counting events like the number of emails received in an hour or the
number of accidents at an intersection in a day.

2/8/2026
3.2.4. Poisson Distribution
Built in function: Poisson Distribution
❖ In R, you can work with the Poisson distribution using the following functions:

❖ dpois(x, lambda): Probability mass function (PMF) : calculates the probability of exactly x
events occurring.

❖ ppois(q, lambda): Cumulative distribution function (CDF): calculates the probability of q or


fewer events occurring.

❖ qpois(p, lambda): Quantile function: calculates the smallest number of events x such that the
probability of x or fewer events is at least p.

❖ rpois(n, lambda): Random number generation: generates n random values from the Poisson
distribution.

2/8/2026
3.2.4. Poisson Distribution
Built in function: Poisson Distribution
❖ In R, you can work with the Poisson distribution using the following functions:

❖ dpois(x, lambda): Probability mass function (PMF) : calculates the probability of exactly x
events occurring.

❖ ppois(q, lambda): Cumulative distribution function (CDF): calculates the probability of q or


fewer events occurring.

❖ qpois(p, lambda): Quantile function: calculates the smallest number of events x such that the
probability of x or fewer events is at least p.

❖ rpois(n, lambda): Random number generation: generates n random values from the Poisson
distribution.

2/8/2026
3.2.4. Poisson Distribution

R function Examples Definition


❖ dpois(3, lambda = 4) ❖ Calculate the probability of exactly 3 events occurring
when the mean rate is λ=4

❖ Calculate the probability of 3 or fewer events


❖ ppois(3, lambda = 4) occurring when the mean rate is λ=4

❖ qpois(0.5, lambda = 4) ❖ Find the smallest number of events x such that the
probability of x or fewer events is at least 0.5,
when λ=4

❖ rpois(10, lambda = 4) ❖ Generate 10 random values from a Poisson distribution


with λ=4

2/8/2026
3.2.4. Poisson Distribution
Built in function: Poisson Distribution (Plotting the Poisson Distribution)
Visualize the PMF or CDF of the Poisson distribution.

❖ PMF Plot
# Parameters

lambda <- 3 # Mean rate of occurrence

# Create a vector of possible events (0 to a reasonable upper limit)

x <- 0:10

# Compute PMF values

pmf_values <- dpois(x, lambda)

# Plot the PMF

barplot(pmf_values, [Link] = x, col = "lightblue",

main = "Poisson PMF (lambda = 3)", xlab = "Number of Events", ylab = "Probability")

2/8/2026
3.2.4. Poisson Distribution
Built in function: Poisson Distribution (Plotting the Poisson Distribution)
Visualize the CDF of the Poisson distribution.

❖ CDF Plot

# Compute CDF values

cdf_values <- ppois(x, lambda)

# Plot the CDF

plot(x, cdf_values, type = "s", col = "blue", lwd = 2, main = "Poisson CDF (lambda = 3)",
xlab = "Number of Events", ylab = "Cumulative Probability")

2/8/2026
3.2.1. Binomial Distribution
Built in function: Binomial Distribution (Plotting the Binomial Distribution)
Comparing Binomial Distributions: Compare binomial distributions with different probabilities or sample sizes.

# Parameters

lambda1 <- 2 # Mean rate of occurrence (1)

lambda2 <- 5 # Mean rate of occurrence (2)

# Create a vector of possible successes (0 to n)

x <- 0:10

# Compute PMF values for both distributions

pmf_values1 <- dpois(x, lambda1)

pmf_values2 <- dpois(x, lambda2)

# Plot the PMFs

barplot(rbind(pmf_values1, pmf_values2), beside = TRUE, col = c("lightblue", "lightgreen"), [Link] = x, main =


"Poisson PMF Comparison", xlab = "Number of Events", ylab = "Probability")

legend("topright", legend = c("lambda = 2", "lambda = 5"), fill = c("lightblue", "lightgreen"))


[Link] in continuous probability distributions
3.3.1. Built in function: Uniform Distribution
➢ The uniform distribution is a continuous ➢ min: Lower bound of the
probability distribution where all outcomes are distribution (default is 0).
equally likely within a specified range. ➢ max: Upper bound of the
➢ dunif(x, min, max): Probability density distribution (default is 1).

function (PDF): calculates the density at x. ➢ x or q: Value at which to

➢ punif(q, min, max): Cumulative distribution evaluate the PDF or CDF.

function (CDF): calculates the probability that a ➢ p: Probability (for quantile

random variable is less than or equal to q. function).

➢ n: Number of random values to


➢ qunif(p, min, max): Quantile function:
generate.
calculates the value x such that the probability of
being less than or equal to x is p.

➢ runif(n, min, max): Random number


generation: generates n random values from the
3.3. Built in continuous probability distributions
3.3.1. Built in function: Uniform Distribution
R function Examples Definition
❖ dunif(0.5, min = 0, max = 1) ❖ Probability Density Function (PDF) Calculate the density
at x=0.5 for a uniform distribution between 0 and 1.

❖ punif(0.5, min = 0, max = 1) ❖ Cumulative Distribution Function (CDF): Calculate the


probability that a random variable is less than or equal to
0.5 for a uniform distribution between 0 and1

❖ qunif(0.7, min = 0, max = 1)


❖ Quantile Function: Find the value x such that the probability of
being less than or equal to x is 0.7, for a uniform distribution
between 0 and 1:
❖ runif(10, min = 0, max = 1)
❖ Random Number Generation: Generate 10 random values from
a uniform distribution between 0 and 1:

2/8/2026
[Link] in continuous probability distributions
3.3.2. Built in function: Exponential and Gamma Distribution
➢ The exponential distribution and gamma distribution are continuous probability
distributions commonly used in statistics.

➢ The exponential distribution is a special case of the gamma distribution.

➢ The exponential distribution models the time between events in a Poisson process (e.g.,
waiting times).

➢ It has one parameter: Rate (λ): The rate parameter, which is the inverse of the mean
(λ=1/mean).
3.3. Built in continuous probability distributions
3.3.2. Built in function: Exponential and Gamma Distribution

R function Definition
❖ dexp(x, rate) ❖ Probability density function (PDF): calculates the density
at x
❖ pexp(q, rate): ❖ Cumulative distribution function (CDF): calculates the
probability that a random variable is less than or equal to q
❖ qexp(p, rate): ❖ Quantile function: calculates the value x such that the
probability of being less than or equal to x is p.
❖ Random number generation: generates n random values
❖ rexp(n, rate): from the exponential distribution.

2/8/2026
3.3. Built in continuous probability distributions
3.3.2. Built in function: Exponential and Gamma Distribution

R function Examples Definition


❖ dexp(2, rate = 0.5) ❖ PDF: Calculate the density at x=2 for an exponential
distribution with rate λ=0.5

❖ pexp(2, rate=0.5) ❖ CDF: Calculate the probability that a random variable is


less than or equal to 2 for an exponential distribution with
rate λ=0.5

❖ qexp(0.7, rate = 0.5) ❖ Quantile Function: Find the value x such that the
probability of being less than or equal to x is 0.7, for an
exponential distribution with rate λ=0.5

❖ rexp(10, rate = 0.5) ❖ Random Number Generation: Generate 10 random


values from an exponential distribution with rate λ=0.5

2/8/2026
[Link] in continuous probability distributions
3.3.2. Built in function: Gamma Distribution
➢ The gamma distribution is a generalization of the exponential distribution and is used to
model waiting times for multiple events.

➢ It has two parameters:

1. Shape (k): Determines the shape of the distribution.

2. Rate (λ): The rate parameter (inverse of the scale parameter).


3.3. Built in continuous probability distributions
3.3.2. Built in function: Exponential and Gamma Distribution

R function Definition
❖ dgamma(x, shape, rate) ❖ Probability density function (PDF) : calculates the
density at x.
❖ pgamma(q, shape, rate) ❖ Cumulative distribution function (CDF): calculates the
probability that a random variable is less than or equal to
q.
❖ qgamma(p, shape, rate)
❖ Quantile function: calculates the value x such that the
probability of being less than or equal to x is p
❖ rgamma(n, shape, rate) ❖ Random number generation: generates n random values
from the gamma distribution.

2/8/2026
3.3. Built in continuous probability distributions
3.3.2. Built in function: Exponential and Gamma Distribution

R function Examples Definition


❖ dgamma(2, shape = 2, rate = 0.5) ❖ PDF: Calculate the density at x=2 for a gamma
distribution with shape k=2 and rate λ=0.5
❖ CDF: Calculate the probability that a random
❖ pgamma(2, shape = 2, rate = 0.5) variable is less than or equal to 2 for a gamma
distribution with shape k=2 and rate λ=0.5

❖ qgamma(0.7, shape = 2, rate = 0.5) ❖ Quantile Function: Find the value x such that the
probability of being less than or equal to x is 0.7, for
a gamma distribution with shape k=2 and rate λ=0.5

❖ rgamma(10, shape = 2, rate = 0.5) ❖ Random Number Generation: Generate 10 random


values from a gamma distribution with
shape k=2 and rate λ=0.5

2/8/2026
[Link] in continuous probability distributions
3.3.3. Built in function: Normal distribution

➢ The normal distribution (also known as the Gaussian distribution) is one of the most
widely used probability distributions in statistics.

➢ It is characterized by its mean (μ) and standard deviation (σ).

Parameters

➢ mean: Mean of the distribution (default is 0).

➢ sd: Standard deviation of the distribution (default is 1).

➢ x or q: Value at which to evaluate the PDF or CDF.

➢ p: Probability (for quantile function).

➢ n: Number of random values to generate.


3.3. Built in continuous probability distributions
3.3.3. Built in function: Normal

R function Definition
❖ dnorm(x, mean, sd) ❖ Probability density function (PDF); calculates the
density at x

❖ pnorm(q, mean, sd) ❖ Cumulative distribution function (CDF) - calculates the


probability that a random variable is less than or equal to q
❖ qnorm(p, mean, sd)
❖ Quantile function - calculates the value x such that the
probability of being less than or equal to x is p

❖ rnorm(n, mean, sd) ❖ Random number generation - generates n random values from
the normal distribution.

2/8/2026
3.3. Built in continuous probability distributions
3.3.3. Built in function: Normal

R function Examples Definition


❖ pdf_value <- dnorm(0, mean = 0, sd = 1)
❖ pdf_value
❖ PDF: Compute the PDF at x = 0 for a normal
distribution with mean = 0 and standard deviation
=1
❖ cdf_value <- pnorm(1, mean = 0, sd = 1)
❖ cdf_value # Print the CDF value ❖ CDF: Compute the CDF at x = 1 for a normal
distribution with mean = 0 and standard deviation
=1
❖ quantile_value <- qnorm(0.975, mean = 0,
sd = 1) ❖ Quantile Function: Compute the quantile for a
❖ quantile_value # Print the quantile value probability of 0.975 for a normal distribution with
mean = 0 and standard deviation = 1
❖ random_numbers <- rnorm(100, mean = 0,
sd = 1) ❖ Random Number Generation: Generate 100
❖ head(random_numbers) # Print the first few random numbers from a normal distribution with
numbers
mean = 0 and standard deviation = 1

2/8/2026
3.3. Built in continuous probability distributions
3.3.3. Built in function: Normal

R function Examples Definition


❖ curve(dnorm(x, mean = 0, sd = 1), from = -
4, to = 4, main = "Normal Distribution ❖ Plotting a Normal Distribution: Plot the PDF of
PDF", xlab = "x", ylab = "Density")
a normal distribution with mean = 0 and standard

❖ random_numbers <- rnorm(1000, mean = deviation = 1


0, sd = 1)
❖ Histogram of Random Numbers: Generate 1000
random numbers from a normal distribution with
❖ hist(random_numbers, breaks = 30, prob =
mean = 0 and standard deviation = 1
TRUE, main = "Histogram of Random
Numbers from Normal Distribution", xlab
= "Value") # Create a histogram

❖ curve(dnorm(x, mean = 0, sd = 1), add =


TRUE, col = "blue", lwd = 2) # Add the
PDF curve to the histogram

2/8/2026
[Link] in continuous probability distributions
3.3.3. Built in function: t distribution

➢ The t-distribution is commonly used in statistics, particularly for small sample sizes or
when the population standard deviation is unknown.

➢ In R, you can work with the t-distribution using functions similar to those for the normal
distribution.
3.3. Built in continuous probability distributions
3.3.3. Built in function: t Distribution

R function Definition
❖ dt(x, df) ❖ Computes the PDF: at x for a t-distribution with df
degrees of freedom.

❖ pt(q, df) ❖ Cumulative distribution function (CDF): Computes the


CDF at q for a t-distribution with df degrees of freedom.
❖ Quantile function: Computes the quantile for a probability p for
❖ qt(p, df)
a t-distribution with df degrees of freedom.

❖ Random number generation: Generates n random numbers


❖ rt(n, df) from a t-distribution with df degrees of freedom.

❖ Plots: the PDF of the t-distribution


❖ curve()

2/8/2026
3.3. Built in continuous probability distributions
3.3.3. Built in function: t Distribution

R function Examples Definition

❖ pdf_value <- dt(0, df = 10)


❖ PDF: Compute the PDF at x = 0 for a t-
❖ pdf_value # Print the PDF value distribution with 10 degrees of freedom

❖ cdf_value <- pt(1.5, df = 10)


❖ CDF: Compute the CDF at x = 1.5 for a t-
❖ cdf_value # Print the CDF value distribution with 10 degrees of freedom

❖ quantile_value <- qt(0.975, df = 10) ❖ Quantile Function: Compute the quantile for a
❖ quantile_value # Print the quantile
probability of 0.975 for a t-distribution with 10
value
degrees of freedom
❖ random_t <- rt(100, df = 10) ❖ Random Number Generation: Generate 100
❖ head(random_t) # Print the first few
numbers random numbers from a t-distribution with 10
degrees of freedom
3.3. Built in continuous probability distributions
3.3.3. Built in function: t distribution

R function Examples Definition


❖ curve(dt(x, df = 10), from = -4, to = 4, col =
❖ Plotting a Normal Distribution: Plot the PDF of
"blue", lwd = 2, main = "t-Distribution vs
Normal Distribution", xlab = "x", ylab = a t-distribution with 10 degrees of freedom
"Density")

❖ curve(dnorm(x, mean = 0, sd = 1), add = ❖ Add the PDF of a standard normal distribution for
TRUE, col = "red", lwd = 2, lty = 2)
comparison

❖ legend("topright", legend = c("t-


Distribution (df = 10)", "Normal ❖ Add a legend
Distribution"), col = c("blue", "red"), lwd
= 2, lty = c(1, 2))
[Link] in continuous probability distributions
3.3.3. Built in function: Chi and F distribution

➢ Chi-Square Distribution: The Chi-square distribution is commonly used in hypothesis


testing, goodness-of-fit tests, and confidence intervals for variance..
3.3. Built in continuous probability distributions
3.3.4. Built in function: Chi and F distribution

R function Definition
❖ dchisq(x, df) ❖ Computes the PDF: Computes the PDF at x for a Chi-
square distribution with df degrees of freedom.

❖ pchisq(q, df) ❖ Cumulative distribution function (CDF): Computes the


CDF at q for a Chi-square distribution with df degrees of
freedom.

❖ qchisq(p, df) ❖ Quantile function: Computes the quantile for a probability p


for a Chi-square distribution with df degrees of freedom

❖ Random number generation: Generates n random numbers


❖ rchisq(n, df)
from a Chi-square distribution with df degrees of freedom.

2/8/2026
3.3. Built in continuous probability distributions
3.3.4. Built in function: Chi and F distribution

R function Examples Definition


❖ pdf_value <- dchisq(3, df = 5)
❖ PDF: Compute the PDF at x = 3 for a Chi-
❖ pdf_value # Print the PDF value
square distribution with 5 degrees of freedom

❖ cdf_value <- pchisq(5, df = 5) ❖ CDF: Compute the CDF at x = 5 for a Chi-square


❖ cdf_value # Print the CDF value
distribution with 5 degrees of freedom

❖ quantile_value <- qchisq(0.95, df = 5)


❖ Quantile Function: Compute the quantile for a
❖ quantile_value # Print the quantile value
probability of 0.95 for a Chi-square distribution
with 5 degrees of freedom
❖ random_chi <- rchisq(100, df = 5)
❖ head(random_chi) # Print the first few ❖ Random Number Generation: Generate 100
numbers
random numbers from a Chi-square distribution
with 5 degrees of freedom
3.3. Built in continuous probability distributions
3.3.4. Built in function: Chi and F distribution

R function Examples Definition


❖ curve(dchisq(x, df = 5), from = 0, to = 20,
❖ Plotting a Chi square Distribution: Plot the
col = "blue", lwd = 2, main = "Chi-Square
Distribution (df = 5)", xlab = "x", ylab = PDF of a Chi-square distribution with 5 degrees
"Density")
of freedom
❖ random_chi <- rchisq(1000, df = 5) ❖ Generate 1000 random numbers from a Chi-
square distribution with 5 degrees of freedom
❖ hist(random_chi, breaks = 30, prob = ❖ Histogram for
TRUE, main = "Histogram of Random
Numbers from Chi-Square Distribution",
xlab = "Value") # Create a histogram

❖ curve(dchisq(x, df = 5), add = TRUE, col =


"blue", lwd = 2) # Add the PDF curve to ❖ Add a legend
the histogram
[Link] in continuous probability distributions
3.3.4. Built in function: F distribution

➢ F Distribution: The F-distribution is commonly used in analysis of variance (ANOVA)


and regression analysis.
3.3. Built in continuous probability distributions
3.3.4. Built in function: F distribution

R function Definition
❖ df(x, df1, df2) ❖ Computes the PDF: Computes the PDF at x for an F-
distribution with df1 and df2 degrees of freedom.

❖ pf(q, df1, df2) ❖ Cumulative distribution function (CDF): Computes the


CDF at q for an F-distribution with df1 and df2 degrees of
freedom.

❖ qf(p, df1, df2) ❖ Quantile function: Computes the quantile for a probability p for
an F-distribution with df1 and df2 degrees of freedom

❖ Random number generation: rf(n, df1, df2): Generates n


❖ rf(n, df1,df2)
random numbers from an F-distribution with df1 and df2 degrees
of freedom..

2/8/2026
3.3. Built in continuous probability distributions
3.3.4. Built in function: F distribution

R function Examples Definition


❖ pdf_value <- df(2, df1 = 5, df2 = 10)
❖ PDF: Compute the PDF at x = 2 for an F-
❖ pdf_value # Print the PDF value
distribution with 5 and 10 degrees of freedom
❖ cdf_value <- pf(3, df1 = 5, df2 = 10)
❖ CDF: Compute the CDF at x = 3 for an F-
❖ cdf_value # Print the CDF value
distribution with 5 and 10 degrees of freedom
❖ quantile_value <- qf(0.95, df1 = 5, df2 = 10) ❖ Quantile Function: Compute the quantile for a
❖ quantile_value # Print the quantile value probability of 0.95 for an F-distribution with 5
and 10 degrees of freedom
❖ Random Number Generation: Generate 100
❖ random_f <- rf(100, df1 = 5, df2 = 10)
❖ head(random_f) # Print the first few random numbers from an F-distribution with 5
numbers
and 10 degrees of freedom
3.3. Built in continuous probability distributions
3.3.4. Built in function: F distribution

R function Examples Definition


❖ Plotting a Chi square Distribution: Plot the
❖ curve(df(x, df1 = 5, df2 = 10), from = 0, to
= 5, col = "red", lwd = 2, main = "F- PDF of an F-distribution with 5 and 10 degrees of
Distribution (df1 = 5, df2 = 10)", xlab =
"x", ylab = "Density") freedom

❖ Generate 1000 random numbers from an F-


❖ random_f <- rf(1000, df1 = 5, df2 = 10)
distribution with 5 and 10 degrees of freedom
❖ hist(random_f, breaks = 30, prob = TRUE, ❖ Histogram : Create a histogram
main = "Histogram of Random Numbers
from F-Distribution", xlab = "Value")

❖ curve(df(x, df1 = 5, df2 = 10), add = ❖ Add a legend: Add the PDF curve to the
TRUE, col = "red", lwd = 2)
histogram
3.4. Examining the distribution of a set of data
➢ When examining the distribution of a dataset in R, you can use a
combination of visualizations and statistical tests to understand the shape,
central tendency, spread, and other characteristics of the data.
Load or Generate Data
➢ If you don't already have a dataset, you can generate one or load an existing
dataset.
➢ Example: Generate a random dataset
➢ [Link] (123) # For reproducibility
➢ data <- rnorm(100, mean = 50, sd = 10) # 100 random numbers from a
normal distribution
➢ Example: Load a dataset (e.g., built-in dataset)
➢ data <- mtcars$mpg # Miles per gallon from the mtcars dataset
3.4. Examining the distribution of a set of data
1. Summary Statistics
➢ Use the summary() function to get basic descriptive statistics.
➢ summary(data) # Get summary statistics
➢ This will provide: Minimum1st, Quartile, Median, Mean3rd, Quartile, Maximum
2. Visualize the Distribution
2..1 Histogram: A histogram is a great way to visualize the shape of the distribution.
➢ hist(data, breaks = 15, col = "lightblue", main = "Histogram of Data", xlab = "Values") #
Create a histogram

2.2. Density Plot: A density plot provides a smoothed version of the histogram.

➢ plot(density(data), main = "Density Plot of Data", xlab = "Values", col = "blue", lwd = 2) #
Create a density plot
3.4. Examining the distribution of a set of data
2. Visualize the Distribution
2.3. Boxplot: A boxplot helps identify outliers and the spread of the data.
➢ boxplot(data, col = "lightgreen", main = "Boxplot of Data", ylab = "Values") #
Create a boxplot

2.4. QQ Plot: A QQ (Quantile-Quantile) plot compares the data distribution to a theoretical


distribution (e.g., normal distribution).

qqnorm(data, main = "QQ Plot of Data") # Create a QQ plot

qline(data, col = "red", lwd = 2) # Add a reference line


3.4. Examining the distribution of a set of data
3. Test for Normality
➢ If you want to test whether the data follows a normal distribution, you can use statistical
tests.
✓ 3.1. Shapiro-Wilk Test: The Shapiro-Wilk test is a formal test for normality.
shapiro_test <- [Link](data) # Perform Shapiro-Wilk test
shapiro_test
If the p-value is less than 0.05, the data is not normally distributed.
✓ 3.2. Kolmogorov-Smirnov Test: This test compares the data to a specified distribution
(e.g., normal distribution).
ks_test <- [Link](data, "pnorm", mean = mean(data), sd = sd(data)) # Perform Kolmogorov-
Smirnov test
ks_test
3.4. Examining the distribution of a set of data
4. Skewness and Kurtosis: Skewness measures the asymmetry of the distribution, and
kurtosis measures the "tailedness.“

[Link]("moments") # Install and load the moments package (if not already installed)

library(moments)

skewness(data) # Compute skewness

kurtosis(data) # Compute kurtosis

5. Compare to Theoretical Distributions: You can overlay a theoretical distribution (e.g.,


normal distribution) on your data to compare.

hist(data, breaks = 15, prob = TRUE, col = "lightblue", main = "Histogram with Normal Curve",
xlab = "Values") # Histogram with normal curve overlay

curve(dnorm(x, mean = mean(data), sd = sd(data)), add = TRUE, col = "red", lwd = 2)


3.5. Simulating the sample distribution of the mean
➢ Simulating the sample distribution of the mean is a fundamental concept in statistics, often
used to demonstrate the Central Limit Theorem (CLT).

➢ The CLT states that the distribution of sample means approximates a normal distribution as
the sample size increases, regardless of the shape of the population distribution.

➢ In R, you can simulate the sample distribution of the mean by repeatedly drawing samples
from a population, calculating their means, and analyzing the distribution of those means.

Steps to Simulate the Sample Distribution of the Mean

1. Define the Population:

✓ Choose a population distribution (e.g., normal, uniform, exponential, etc.).

✓ Specify the population parameters (e.g., mean, standard deviation).


3.5. Simulating the sample distribution of the mean
Steps to Simulate the Sample Distribution of the Mean

2. Set Simulation Parameters:


✓ Choose the sample size (n) for each sample.

✓ Choose the number of samples (num_samples) to draw.

3. Simulate the Sampling Process:

✓ Repeatedly draw samples from the population.

✓ Calculate the mean of each sample.

4. Analyze the Distribution of Sample Means:

✓ Plot a histogram of the sample means.

✓ Compare the distribution of sample means to a normal distribution.


3.5. Simulating the sample distribution of the mean
Example: Simulating the Sample Distribution of the Mean

1. Define the Population: Let's assume the population follows a non-normal


distribution (e.g., exponential distribution with rate = 0.2).

# Population parameters

rate <- 0.2 # Rate parameter for exponential distribution

population_mean <- 1 / rate # Theoretical mean of exponential distribution

population_sd <- 1 / rate # Theoretical standard deviation of exponential distribution

2. Set Simulation Parameters: We'll draw 10,000 samples, each of size 30.

# Simulation parameters

n <- 30 # Sample size

num_samples <- 10000 # Number of samples to draw


3.5. Simulating the sample distribution of the mean
3. Simulate the Sampling Process: Draw samples from the population and calculate
their means.

# Initialize a vector to store sample means

sample_means <- numeric(num_samples)

# Simulate the sampling process

[Link](123) # For reproducibility

for (i in 1:num_samples) {

sample <- rexp(n, rate = rate) # Draw a sample from the exponential distribution

sample_means[i] <- mean(sample) # Calculate the mean of the sample

}
3.5. Simulating the sample distribution of the mean
4. Analyze the Distribution of Sample Means
✓ Histogram of Sample Means: Plot a histogram of the sample means to visualize their

distribution.

# Plot the histogram of sample means

hist(sample_means, breaks = 30, prob = TRUE, col = "lightblue",

main = "Sampling Distribution of the Mean", xlab = "Sample Means")

# Overlay the theoretical normal distribution


curve(dnorm(x, mean = population_mean, sd = population_sd / sqrt(n)),

add = TRUE, col = "red", lwd = 2)

# Add a legend
legend("topright", legend = c("Sample Means", "Theoretical Normal"),

col = c("lightblue", "red"), lwd = 2)


3.5. Simulating the sample distribution of the mean
4. Analyze the Distribution of Sample Means
✓ QQ Plot: Compare the distribution of sample means to a normal distribution using a QQ plot.

# QQ plot of sample means

qqnorm(sample_means, main = "QQ Plot of Sample Means")

qqline(sample_means, col = "red", lwd = 2)


✓ Summary Statistics: Calculate the mean and standard deviation of the sample means.

mean_sample_means <- mean(sample_means) # Mean of sample means

sd_sample_means <- sd(sample_means) # Standard deviation of sample means (standard error)

cat("Mean of sample means:", mean_sample_means, "\n") # Print results

cat("Standard deviation of sample means:", sd_sample_means, "\n")


3.5. Simulating the sample distribution of the mean
4. Full Code

# Population parameters
rate <- 0.2
population_mean <- 1 / rate
population_sd <- 1 / rate
# Simulation parameters
n <- 30
num_samples <- 10000
# Simulate sample means
[Link](123)
sample_means <- replicate(num_samples, mean(rexp(n, rate)))
# Histogram of sample means
hist(sample_means, breaks = 30, prob = TRUE, col = "lightblue",
main = "Sampling Distribution of the Mean", xlab = "Sample Means")
curve(dnorm(x, mean = population_mean, sd = population_sd / sqrt(n)),
add = TRUE, col = "red", lwd = 2)
legend("topright", legend = c("Sample Means", "Theoretical Normal"),
col = c("lightblue", "red"), lwd = 2)
# QQ plot of sample means
qqnorm(sample_means, main = "QQ Plot of Sample Means")
qqline(sample_means, col = "red", lwd = 2)
# Summary statistics
mean_sample_means <- mean(sample_means)
sd_sample_means <- sd(sample_means)
cat("Mean of sample means:", mean_sample_means, "\n")
cat("Standard deviation of sample means:", sd_sample_means, "\n")
4. Descriptive statistics
4.1. Summary statistics

➢ Summary statistics provide a quick overview of the main


characteristics of a dataset, such as central tendency, dispersion, and
shape.

➢ In R, you can calculate summary statistics using built-in functions


and packages.

➢ Basic Summary Statistics: Use the summary() function to get a quick


overview of a dataset.
Example:

data <- mtcars #Using the built-in mtcars dataset

summary(data) # Get summary statistics


4. Descriptive statistics
4.1. Summary statistics

➢ Descriptive Statistics with psych Packages


[Link]("psych") #Install and load the psych package

library(psych)
describe(data) # Get descriptive statistics
➢ Grouped Summary Statistics: You can calculate summary statistics for groups using the dplyr package
[Link]("dplyr") # Install and load the dplyr package
library(dplyr)
data %>% # Group by 'cyl' and calculate summary statistics for 'mpg'
group_by(cyl) %>%
summarise(
mean_mpg = mean(mpg),
median_mpg = median(mpg),
sd_mpg = sd(mpg),
min_mpg = min(mpg),
max_mpg = max(mpg))
4. Descriptive statistics
4.1. Summary statistics

[Link]("moments") # Install and load the moments package

library(moments)

skewness(data$mpg) # Skewness

kurtosis(data$mpg) # Kurtosis

cor(data) # Compute correlation matrix


4.2 Graphics procedures
4.2.1. High-Level Plotting Commands

➢ High-level plotting commands create complete plots with a single function call.

➢ They are designed to quickly generate standard visualizations without requiring

detailed customization.

Examples of High-Level Plotting Functions:

plot() #Generic function for creating scatterplots, line plots, and more.

hist() # Creates histograms.

boxplot() # Creates boxplots.

barplot() # Creates bar plots.

pie() # Creates pie charts.


4.2 Graphics procedures
4.2.1. High-Level Plotting Commands
➢ # Create a scatterplot
plot(mtcars$wt, mtcars$mpg, main = "Scatterplot of Weight vs MPG", xlab = "Weight", ylab =
"MPG", pch = 16, col = "blue")

# Create a histogram
hist(mtcars$mpg, main = "Histogram of MPG", xlab = "MPG", col = "lightblue", breaks = 10)

# Create a boxplot
boxplot(mpg ~ cyl, data = mtcars, main = "Boxplot of MPG by Cylinder", xlab = "Cylinders",
ylab = "MPG", col = "lightgreen")
4.2 Graphics procedures
4.2.1. Low-Level Plotting Commands
➢ Low-level plotting commands: add elements to an existing plot. They are used to customize
or enhance high-level plots.

Examples of Low-Level Plotting Functions

points() Adds points to an existing plot.

lines() Adds lines to an existing plot.

abline() Adds straight lines (e.g., regression lines, reference lines).

text() Adds text annotations to a plot.


4.2 Graphics procedures
4.2.1. Low-Level Plotting Commands
➢ Example: Adding Elements to a Plot

➢ # Create a scatterplot

➢ plot(mtcars$wt, mtcars$mpg, main = "Scatterplot of Weight vs MPG", xlab = "Weight", ylab


= "MPG", pch = 16, col = "blue")

➢ # Add a regression line

➢ abline(lm(mpg ~ wt, data = mtcars), col = "red", lwd = 2)

➢ # Add text annotations

➢ text(4, 25, "Heavy Cars", col = "darkred")

➢ # Add a legend

➢ legend("topright", legend = "Regression Line", col = "red", lwd = 2)


4.2 Graphics procedures
4.2.1. Interactive Plotting Commands
➢ Interactive plotting commands allow users to interact with plots, such as zooming,
panning, or clicking to explore data points.

➢ These are often implemented using specialized packages.


➢ Examples of Interactive Plotting Packages:

Plotly #Creates interactive plots (e.g., scatterplots, line plots, bar plots).

ggplot2 + plotly #Converts ggplot2 plots to interactive plots.

shiny #Builds interactive web applications with R.

[Link]("plotly") # Install and load the plotly package

library(plotly)

➢ # Create an interactive scatterplot

p <- plot_ly(data = mtcars, x = ~wt, y = ~mpg, type = "scatter", mode = "markers", color =
~cyl)

p
4.2 Graphics procedures
4.2.1. Interactive Plotting Commands
➢ # Install and load ggplot2 and plotly

[Link]("ggplot2")

[Link]("plotly")

library(ggplot2)

library(plotly)

➢ # Create a ggplot2 plot

gg <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +

geom_point() +labs(title = "Scatterplot of Weight vs MPG", x = "Weight", y = "MPG")

➢ # Convert to an interactive plot

ggplotly(gg)

You might also like