Statistical computing II Note
Statistical computing II Note
Department of Statistics
Bahir Dar-Ethiopia
March, 2026
2/8/2026
Learning Objectives
Familiarity with R
Explore, visualize, analyze data &
Run basic models in R
2/8/2026
1 Introduction to
2/8/2026
1.1 Introduction
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.
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.
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
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
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.
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.
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.
• 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:
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.
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.
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.
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.
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.
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.
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.
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.
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
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:
} 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
} else { print("Negative")
} 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):
2/8/2026
2.1.1. Repetitive Execution
Example: Combine Conditions and Loops: Check if numbers in a vector are positive or negative:
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.
➢ R has a large number of in-built functions and the user can create their own functions.
➢ 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.
2/8/2026
2.2-2.4 R - Functions
Function Components
❖ 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.
➢ 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.
❖ 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.
➢ 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)
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_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
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
➢ 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
➢ 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.
➢ The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times
is estimated during the binomial distribution.
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
❖ pbinom(): This function gives the cumulative probability of an event. It is a single value
representing the probability.
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
x <- 0:n
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
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
x <- 0:n
❖ 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
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(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:
❖ rgeom(n, prob): Random number generation - generates n random values from the
geometric distribution.
➢ So, if you want the number of trials until the first success, you need to add 1 to the result.
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.
❖ 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.
❖ 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
❖ 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
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
x <- 0:10
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
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
x <- 0:10
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 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
❖ 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
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.
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
❖ 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
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.
Parameters
R function Definition
❖ dnorm(x, mean, sd) ❖ Probability density function (PDF); calculates the
density at x
❖ 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
2/8/2026
3.3. Built in continuous probability distributions
3.3.3. Built in function: Normal
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.
2/8/2026
3.3. Built in continuous probability distributions
3.3.3. Built in function: t Distribution
❖ 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
❖ 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
R function Definition
❖ dchisq(x, df) ❖ Computes the PDF: Computes the PDF at x for 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 Definition
❖ df(x, df1, df2) ❖ Computes the PDF: Computes the PDF at x 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
2/8/2026
3.3. Built in continuous probability distributions
3.3.4. Built in function: F distribution
❖ 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
[Link]("moments") # Install and load the moments package (if not already installed)
library(moments)
hist(data, breaks = 15, prob = TRUE, col = "lightblue", main = "Histogram with Normal Curve",
xlab = "Values") # Histogram with normal curve overlay
➢ 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.
# Population parameters
2. Set Simulation Parameters: We'll draw 10,000 samples, each of size 30.
# Simulation parameters
for (i in 1:num_samples) {
sample <- rexp(n, rate = rate) # Draw a sample from the exponential distribution
}
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.
# Add a legend
legend("topright", legend = c("Sample Means", "Theoretical Normal"),
# 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
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
library(moments)
skewness(data$mpg) # Skewness
kurtosis(data$mpg) # Kurtosis
➢ High-level plotting commands create complete plots with a single function call.
detailed customization.
plot() #Generic function for creating scatterplots, line plots, and more.
# 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.
➢ # Create a scatterplot
➢ # Add a legend
Plotly #Creates interactive plots (e.g., scatterplots, line plots, bar plots).
library(plotly)
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)
ggplotly(gg)