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

Module 1 Lecture Notes-2

The document outlines a course on Engineering Statistics and Data Analytics, focusing on the application of R programming for data analysis in engineering contexts. It covers fundamental concepts such as descriptive statistics, probability distributions, statistical inference, regression, and data visualization, with practical sessions for hands-on experience. The course aims to equip students with skills to analyze data, perform statistical modeling, and effectively communicate findings using R.

Uploaded by

hannahake17
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 views33 pages

Module 1 Lecture Notes-2

The document outlines a course on Engineering Statistics and Data Analytics, focusing on the application of R programming for data analysis in engineering contexts. It covers fundamental concepts such as descriptive statistics, probability distributions, statistical inference, regression, and data visualization, with practical sessions for hands-on experience. The course aims to equip students with skills to analyze data, perform statistical modeling, and effectively communicate findings using R.

Uploaded by

hannahake17
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

ENGINEERING STATISTICS AND DATA ANALYTICS – GET 305

PROF. FRANK EDUGHOM EKPAR

MODULE 1

Overview of Engineering Statistics and Data Analytics; Introduction to R Programming


and Application of R Programming to Engineering Statistics and Data Analytics

1. Overview of Engineering Statistics and Data Analytics


2. Overview of R environment and tools
3. R Keywords and Variables
4. Data types and structures: Vectors, Matrices, Factors, Data Frames, Arrays and Other R
Collections (Lists)
5. R as a calculator – basic arithmetic
6. Iteration and looping structures (for, while, repeat)
7. Conditional statements (if, if-else, switch)
8. Functions in R – creating, using, and extending functions
9. The Apply Family of functions (apply, lapply, sapply, tapply, mapply)
10. Data visualization and reporting in R

1
Overview of Engineering Statistics and Data Analytics

Modern society is increasingly data-driven. Algorithms and the data they operate on now
control a vast and ever-increasing array of processes and systems. These data-intensive systems
rely on statistical methods to process the data that drive them and to provide actionable insights
to support effective decision making, design, manufacturing and engineering processes.
The tools generated by Engineering Statistics and Data Analytics find application in practically
all aspects of modern life including, but not limited to, Aviation and Aerospace Engineering,
Space Exploration, Banking and Financial Markets, Medicine and Healthcare, Robotics and
Automation, Quantum Mechanics and Applications as well as research and development in
science and engineering and other aspects of society.
In creating the innovative groundbreaking three-dimensional multilayer
electroencephalography (EEG) systems, also known as Ekpar Electroencephalography (Ekpar
EEG) systems with far-reaching implications for a broad range of fields from medicine to
computing and beyond, Professor Frank Edughom Ekpar relied in part on statistical methods
in correlation analysis and data visualization and reporting to demonstrate the effectiveness of
Ekpar EEG systems.

Subject A: Scatter plot of EEG data (in microvolts) for SE1-SE2 electrode pair.
Correlation coefficient, r = 0.2951.
Source: Frank Edughom Ekpar. A Novel Three-dimensional Multilayer
Electroencephalography Paradigm. Fortune Journal of Health Sciences, 7 (3), (2024): 466-
480. URL (FREE PDF): [Link]
[Link]

2
Topics To Be covered In The Entire Engineering Statistics And Data Analytics Course

Descriptive statistics, frequency distribution, populations and sample, central tendency,


variance data sampling, mean, median, mode, mean deviation, percentiles, etc. Probability.
Binomial, poison hyper-geometric, normal distributions, etc. Statistical inference intervals, test
hypothesis and significance. Regression and correlation. Introduction to big data analytics and
cloud computing applications. Introduction to the R language; R as a calculator; Vectors,
matrices, factors, data frames and other R collections. Iteration and looping control structures.
Conditionals and other controls. Designing using and extending functions. The Apply Family.
Statistical modelling and inference in R.

Course Learning Outcomes (CLOs)


By the end of this course, students will be able to:
1. Explain the fundamental concepts of descriptive statistics, probability, and data analysis in
engineering contexts.
2. Apply probability distributions (Binomial, Poisson, Hypergeometric, Normal, etc.) to
model real-life engineering problems.
3. Perform statistical inference, including hypothesis testing, confidence intervals, and
analysis of variance.
4. Analyze relationships in data using correlation and regression techniques for engineering
applications.
5. Demonstrate an understanding of big data analytics and cloud computing applications in
engineering.
6. Use R programming language for data manipulation, statistical analysis, and visualization.
7. Develop simple statistical models in R to solve engineering problems.
8. Communicate statistical findings and analytical results effectively using appropriate
visualization and reporting tools.

Course Outcomes (Cos)

On successful completion of the course, students will be able to:


1. Describe and summarize data using measures of central tendency, dispersion, and
frequency distributions.
2. Apply probability theory and statistical distributions to solve engineering-related problems.
3. Construct confidence intervals and perform hypothesis testing for decision-making.
4. Use regression and correlation techniques to analyze engineering datasets.
5. Demonstrate knowledge of big data analytics concepts and their applications in cloud-based
environments.
6. Implement statistical computations and visualizations using R programming.
7. Build and interpret statistical models in R for engineering problem-solving.
8. Work collaboratively to apply statistical and analytical methods to real-world engineering
data.

3
Course Outline (Modules)

Module 1: Overview of Engineering Statistics and Data Analytics; Introduction to R


Programming and Application of R Programming to Engineering Statistics and Data
Analytics
1. Overview of Engineering Statistics and Data Analytics
2. Overview of R environment and tools
3. R Keywords and Variables
4. Data types and structures: Vectors, Matrices, Factors, Data Frames, Arrays and Other R
Collections
5. R as a calculator – basic arithmetic
6. Iteration and looping structures (for, while, repeat)
7. Conditional statements (if, if-else, switch)
8. Functions in R – creating, using, and extending functions
9. The Apply Family of functions (apply, lapply, sapply, tapply, mapply)
10. Data visualization and reporting in R

Module 2: Introduction to Statistics and Data Analysis


1. Role of statistics in engineering and data analytics
2. Populations, samples, and data types
3. Descriptive statistics: central tendency (mean, median, mode)
4. Measures of dispersion: range, variance, standard deviation, mean deviation
5. Percentiles, quartiles, and frequency distributions

Module 3: Probability Theory and Distributions


1. Basic probability concepts and rules
2. Conditional probability and Bayes’ theorem
3. Random variables (discrete and continuous)
4. Discrete distributions: Binomial, Poisson, Hypergeometric
5. Continuous distributions: Normal, Exponential, Uniform

Module 4: Statistical Inference


1. Sampling distributions
2. Confidence intervals and estimation
3. Hypothesis testing – one-sample and two-sample tests
4. Tests of significance (Z, t, Chi-square, F-tests)
5. Analysis of variance (ANOVA)

Module 5: Regression and Correlation


1. Correlation analysis (Pearson and Spearman)
2. Simple linear regression
3. Multiple regression analysis
4. Model fitting and goodness of fit
5. Applications in engineering problem-solving

4
Module 6: Introduction to Data Analytics
1. Overview of data analytics in engineering
2. Introduction to big data analytics
3. Applications of cloud computing in data analytics

Module 7: Case Studies in Engineering Statistics

Module 8: Case Studies in Data Analytics

Mode of Delivery
• Lectures: Theoretical concepts of statistics, probability, and analytics
• Laboratory/Practical Sessions: Hands-on statistical computation and data analytics in R
• Tutorials & Problem-Solving Sessions: Worked examples and case studies
• Assignments & Group Projects: Application of concepts to engineering data

Assessment Methods
• Mid-Semester Examination (30%) – Covers substantially all key aspects of the course
• Final Examination (70%) – Comprehensive coverage of all modules

5
Introduction to the R Programming Language

What is R?

The R programming language is a cross-platform, open source and currently free programming
language suitable for statistical computing, graphics and data visualization. R is an interpreted
language.

Developing With the R Programming Language (R Language and R Studio Integrated


Development Environment (IDE))

The R programming language can be downloaded from: [Link]


After installing the R language on a platform such as Microsoft Windows, users can access the
R Console by launching the associated executable program.

Appearance of the R Console.

Users can type in R source code at the prompt within the R Console and press ENTER to have
the source code interpreted and executed. Results are typically displayed within the R Console
or in a separate window as required.

6
Development can be simplified using the R Studio Integrated Development Environment (IDE)
available from: [Link]
The R Studio IDE combines the tools required to make the use of the R programming language
easier.

Screenshot of R Studio Integrated Development Environment.

R Keywords

R keywords are special or reserved words or symbols with predefined meanings. Keywords
should not be used as names of variables, functions or other identifiers in R programming. Note
that since R is a case-sensitive language, variations in case can be utilized to create acceptable
identifiers that are similar to keywords, although this practice is discouraged. For example,
although TRUE is a keyword representing a logical constant, True or true could be used as a
variable name. However, to avoid confusion with keywords, the use of such variations is
discouraged.

The following are examples of R keywords:

7
if, else, repeat, while, for, in, next, break, function, return
TRUE, FALSE, NULL, Inf, NaN, NA
NA_integer_, NA_real_, NA_complex_, NA_character_

Variables

Variables are names or symbols used to store data, values and the results of expressions in R.
Variables are case-sensitive. They can start with alphanumeric characters and contain a mixture
of alphanumeric characters and numbers without spaces between them. Keywords cannot be
used as variables.

Examples

X <- 5
first_name <- "Ebiye"
last_name <- "Sekibo"

Here, the variable named X is assigned a value of 5. The assignment operator typically
utilized in R programming is <- (less minus) although the more common = can also be used.
The variable named first_name is assigned the value "Ebiye" while the variable named
last_name is assigned the value "Sekibo".

new_number <- 7

Z <- X + new_number

#Z equals 12

full_name <- paste(first_name, last_name)


#full_name equals "Ebiye Sekibo"
#Note that the paste() command is used to concatenate items

8
#The print() command can be used to print output to the R console.
print(full_name) #Prints "Ebiye Sekibo"

Comments In R
The # symbol is used to include comments in R programs in a single line of text. Information
supplied after the # sign is ignored and not used to evaluate the program. The # symbol can be
repeated on multiple lines to simulate multiline comments in R.

Data Types and Structures in R: Vectors, Matrices, Factors, Data Frames, Arrays and
Other R Collections (Lists)

Vectors
Vectors are used to represent a collection of data items of the same type (homogenous) in R.
The items themselves could be numeric, character or logical types.
Vectors are one-dimensional (1D) data structures in R. Vectors are defined using the c
command followed by paratheses or brackets containing a listing of the elements of the vector.

Examples:
my_vector <- c(8, 5, 7, 19, 25)
string_vector <- c("Banana", "Mango", "Udara", "Guava")

Length of a Vector: Number of Elements in a Vector

The length of a vector is the number of elements in the vector.


The length() command can be used to determine the number of elements in a vector.
number_of_elements <- length(my_vector) #number_of_elements now has a value of 5.
number_of_strings <- length(string_vector) #number_of_strings now has a value of 4.

9
Accessing Vector Elements
Square brackets – [] – are used to access vector elements by index. The index of the desired
element is placed in the square braces appearing immediately after the variable name
representing the vector. Vector element indices start from 1, that is, R uses 1-based indexing.

Using the examples of vectors given above:

my_vector[3] refers to the third element of the my_vector vector which has a value of 7.
string_vector[2] refers to the second element of the string_vector vector which has a value of
"Mango".

my_vector[3] <- 10 #Changes the third element of the my_vector vector to a value of 10.

Matrices

A matrix in R is a two-dimensional (2D) data structure with rows and columns that is used to
store items of the same type (homogenous). Matrices are created using the matrix command.

my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3,


byrow = FALSE,
dimnames = list(c("Row1", "Row2"), c("Col1", "Col2", "Col3")))

1 3 5
2 4 6

The vector contains the elements or data in the rows and columns of the matrix.
nrow represents the number of rows in the matrix while ncol represents the number of columns
in the matrix.
byrow is used to specify whether the matrix should be filled by row (TRUE) or by column
(FALSE). The default value of byrow is FALSE.
dimnames is a list that specifies the names of the rows and columns. It is optional.

10
Here, we change the value of the byrow argument to TRUE for the same matrix data given
above and note that the arrangement of elements in the matrix changes accordingly.
my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3,
byrow = TRUE)

1 2 3
4 5 6

Accessing Matrix Elements In R

Accessing A Single Element:


To access a specific element, provide its row and column number.
# Access the element in the second row, third column
element <- my_matrix[2, 3]
print(element) #Prints out 6

Arrays
Arrays represent a generalization of matrices to more than two dimensions. All elements within
an array must be of the same data type.

my_array <- array(1:24, dim = c(2, 3, 4)) # A 2x3x4 array containing elements from 1 to 24.

The dim vector specifies the dimensions of the array.

Accessing elements within an R array is accomplished using square brackets [] and specifying
the indices for each dimension. R uses 1-based indexing. This means that the first element is at
index 1, the second element is at index 2, and so on.

General Syntax for Multi-Dimensional Arrays:


array_name[row_index, column_index, matrix_level_index, ...]

11
Accessing A Specific Element.
To access the element in the first row, third column of the second matrix:
my_array <- array(1:24, dim = c(2, 3, 4)) # A 2x3x4 array containing elements from 1 to 24.
element <- my_array[1, 3, 2]
print(element) #Prints out 11

Factors
Factors are one-dimensional (1D) data structures used to store categorical data with predefined
levels. Internally, factors are stored as integers associated with labels.
gender_factor <- factor(c("Male", "Female", "Male", "Female"), levels = c("Male", "Female"))

Data Frames
In R, a data frame is similar to a table in a spreadsheet. A data frame can hold different types
of data across multiple columns. Each column in a data frame is essentially a vector, and all
columns must have the same number of rows.

Name <- c("Nwachukwu", "Musa", "Adebayo")


Language <- c("Igbo", "Hausa", "Yoruba")
Age <- c(39, 23, 70)

my_dataframe <- [Link](Name, Language, Age)


print(my_dataframe)

my_dataframe above has 3 columns (Name, Language, and Age) each of which has 3 rows.

another_dataframe <- [Link](


Name = c("Alice", "Bob"),
Age = c(25, 30),
IsStudent = c(TRUE, FALSE)
)
another_dataframe above has 3 columns (Name, Age, and IsStudent) each of which has 2 rows.

12
Accessing Elements In A Data Frame

Accessing Columns:

Using the dollar sign ($): This is a common and intuitive way to access a column by its name.

# Example: Accessing the 'Name' column of a data frame named 'my_dataframe'


my_dataframe$Name

Using double square brackets [[]]: This also accesses a column by its name and returns it as
a vector.

# Example: Accessing the 'Age' column of a data frame named 'my_dataframe'


my_dataframe[["Age"]]

Using single square brackets []: This can access a column by its index or name, but it returns
a data frame (even if it is a single column).

# Example: Accessing the first column by index


my_dataframe[1]

# Example: Accessing the 'Name' column by name


my_dataframe["Name"]

Accessing Rows:
Using single square brackets []: Here row indices can be specified before the comma within
the brackets.

# Example: Accessing the first two rows of 'my_dataframe'


my_dataframe[1:2, ]

13
# Example: Accessing a specific row (e.g., the third row)
my_dataframe[3, ]

Using logical conditions: Rows can be selected based on conditions applied to a column.

# Example: Selecting rows where 'Age' is greater than 25


my_dataframe[my_dataframe$Age > 25, ]

Accessing Specific Elements:


Using single square brackets []: Combine row and column indices to access a specific cell.

# Example: Accessing the element in the second row and third column
my_dataframe[2, 3]

# Example: Accessing the 'Age' of the first row


my_dataframe[1, "Age"]

Other R Collections (Lists)


R lists are used to store collections of objects that can be of different or heterogenous types.
Lists can contain various types of objects including vectors, matrices, lists and functions.
Lists are one-dimensional (1D) data structures in R.

my_r_list <- list("name" = "Ebiye Sekibo", "level" = 300, "age" = 25, "scores" = c(77, 85, 67,
95, 80))

The list above is designed to represent a student aged 25 years in 300 level with a set of scores
for a given semester and contains a string named name with a value of Ebiye Sekibo, a number
named level with a value of 300, a number named age with a value of 25 and a vector named
scores with the sequence: 77, 85, 67, 95 and 80.

14
Accessing Elements In R Lists
There are several methods for access to the elements in a list.

Using Double Square Brackets [[]]:


This method extracts the actual element from the list, removing the list structure around it. It
is suitable when you need the underlying object directly.

# Access and print the first element in the list given earlier
print(my_r_list[[1]]) #Prints "Ebiye Sekibo"
# Access and print the fourth element
print(my_r_list[[4]]) #Prints the vector: 77, 85, 67, 95, 80

Using the Dollar Sign $ (for named elements):


For explicitly named list elements, the element names can be used to access the elements
directly by using their names with the dollar sign operator. This method also extracts the
underlying object.

# Access and print the element named "name" in the list given earlier
print(my_r_list$name) #Prints "Ebiye Sekibo"
# Access and print the element named "scores"
print(my_r_list$scores) #Prints the vector: 77, 85, 67, 95, 80

Using Single Square Brackets []:


This technique returns a sub-list containing the specified elements. It extracts one or more
elements but still retains the list structure.

# Returns a list containing the first element


print(my_r_list[1]) #Prints $name "Ebiye Sekibo"
# Returns a list containing the first and second elements
print(my_r_list[c(1, 2)]) #Prints $name "Ebiye Sekibo" $level 300

15
R As A Calculator – Basic Arithmetic

R can be used as a calculator to evaluate arithmetic expressions using well-known operators


for addition (+), subtraction (-), multiplication (*), division ( / ) and exponentiation (^). R also
supports modular arithmetic operations (integer remainder - %%) and integer division ( %/%
).

The order of arithmetic operations complies with the PEDMAS (Parenthesis, Exponents,
Division, Multiplication, Addition and Subtraction) convention.

PEDMAS is popularly known as BODMAS: Bracket, Of, Division, Multiplication, Addition


and Subtraction.

7+6*5
results in 37 while
(7 + 6) * 5
results in 65
x <- 4
cube_of_x <- x ^ 3
print(cube_of_x) #Prints out 64

Iteration And Looping Structures (for, while, repeat)

Iteration and looping or repetition are achieved by repeatedly executing a block of code. This
technique can be used to efficiently process multiple elements of a data structure or to perform
a given task a specified number of times.

for Loop
This can be used to iterate over the elements of a sequence such as a vector, list or data frame
or to repeat a block of code for a known number of iterations.

Examples:
data_vector <- c(1, 2, 3, 4, 5, 6, 7)

for(item in data_vector)
{

16
print(item)
}

number_of_items <- length(data_vector)


for(i in 1:number_of_items)
{
print(data_vector[i])
}

#Print out the square of each integer in the range 1 to 10


for(i in 1:10)
{
print(i ^ 2)
}

#Generic form of for loop in R


for(variable in sequence)
{
code_block
}

while Loop in R

while Loop:
The while loop repeatedly executes a block of code as long as a specified condition remains
TRUE. The while loop can be used when the number of iterations is not known beforehand and
depends on a condition being met.

#Generic form of while loop in R


while(condition_is_true)
{
code_block
}

Examples:

counter <- 1
maximum_count <- 10
while (counter <= maximum_count)
{
print(paste("Current counter value: ", counter))
counter <- counter + 1
}

17
#Compute sum of first 10 non-zero whole numbers.
sum <- 0
current_number <- 1
last_number <- 10
while (current_number <= last_number)
{
sum <- sum + current_number
current_number <- current_number + 1
}
print(paste("Sum of first 10 non-zero whole numbers: ", sum))

repeat Loop:
The repeat loop executes a block of code indefinitely until an explicit break statement is
encountered within the loop body. The repeat loop is used when a loop needs to run at least
once and the termination condition is checked inside the loop.

Example:

x <- 1
max_x <- 20
repeat
{
print(x)
x <- x + 1
if (x >= max_x)
{
break
}
}

Conditional Statements (if, if-else, switch)

Conditional statements are used to control the flow of execution of a program in R. Conditional
statements in R programming allow for the execution of different code blocks based on whether
a specified condition evaluates to TRUE or FALSE, enabling decision-making within programs
and controlling the flow of execution.

if Statement:
The if statement executes a block of code only if the given condition is TRUE.

Example
x <- 20
if (x < 100)
{
print("x is less than 100")
}

18
Generic form of if statement:
if(condition_is_true)
{
code_block
}

if-else Statement:
The if-else statement provides an alternative code block to execute when the if condition is
FALSE.

y <- 45
if (y > 20)
{
print("y is greater than 20")
}
else
{
print("y is not greater than 20 ")
}

else if Ladder:
For multiple conditions, the else if ladder allows for checking subsequent conditions if the
preceding if or else if conditions are FALSE.

score <- 67
if (score >= 70)
{
print("Grade A")
}
else if (score >= 60)
{
print("Grade B")
}
else if(score >= 50)
{
print("Grade C")
}
else if(score >= 45)
{
print("Grade D")
}
else if(score >= 40)
{
print("Grade E")
}
else
{

19
print("Grade F")
}

ifelse() Function (for vectorized operations):


The ifelse() function can be used to apply conditional logic across entire vectors, returning a
vector of results.

numbers <- c(9, 2, 7, 5, 1, 3, 2, 4)


result <- ifelse(numbers > 7, "Greater than 7", "Not greater than 7")
print(result)

switch() Statement:
The switch() statement is used when there is a need to select one of several code blocks to
execute based on the value of a single expression.

Generic Form:
switch(expression, case1, case2, case3, ...)

expression:
This is the value or variable that switch() will evaluate. It can be either a character string or a
number.

case1, case2, ...:


These are the potential outcomes or actions. They can be named or unnamed.
• If expression is a character string: switch() attempts to match the string value of
expression exactly with the names of the case arguments. If a match is found,
the value associated with that named argument is returned. If there are multiple
matches, the first one found is returned.
• If expression is a number: The number is coerced to an integer. switch() then
uses this integer as an index to select the corresponding case argument. For
example, if expression evaluates to 3, the third case argument is evaluated and
its value returned. If the integer is outside the range of available cases (e.g., less
than 1 or greater than the number of cases), NULL is returned.

Key characteristics:
• No break statements: Unlike switch statements in some other languages, switch() in R
does not require break statements. Only the matching case is executed.
• No explicit default: There is no dedicated default case. However, an unnamed argument
can serve as a default if no other match is found when expression is a character string.
If expression is numeric and no match is found, NULL is returned.
• Return value: The switch() function returns the value of the selected case.

Examples:

choice <- 3
result <- switch(choice,
"First option",

20
"Second option",
"Third option"
)
print(result)

day <- "Friday"


result <- switch(day,
"Monday" = "Start of the week",
"Friday" = "End of the week",
"Weekend")
print(result)

Functions in R – Creating, Using, And Extending Functions

Functions are blocks of code that can enable efficient organization, maintenance and reuse of
code in R programs.

They are created as named entities using the function keyword followed by parentheses
(circular brackets) which may contain a list of parameters.

The function body is typically delineated by curly {} brackets and may contain any number of
statements.

Function names can start with alphanumeric characters and may contain a combination of
alphanumeric characters and numbers without spaces. R keywords cannot be used as function
names.

Additionally, R comes bundled with a set of built-in functions. Examples of in-built R functions
include, but are not limited to, the following:

Examples of built-in R functions:

Common Categories of Built-in R Functions:


• Mathematical Functions:
o abs(x): Returns the absolute value.
o sqrt(x): Calculates the square root.
o log(x), log10(x): Natural logarithm and base-10 logarithm, respectively.
o exp(x): Calculates e raised to the power of x.
o sin(x), cos(x), tan(x): Trigonometric functions.
o round(x, digits), ceiling(x), floor(x), trunc(x): Rounding and integer extraction.
• Statistical Functions:
o mean(x), median(x): Calculates the mean and median.
o sd(x), var(x): Calculates the standard deviation and variance.
o sum(x), min(x), max(x): Calculates the sum, minimum, and maximum.
o range(x): Returns the minimum and maximum values.
o quantile(x, probs): Calculates quantiles.

21
o Functions for probability distributions (e.g., dnorm, pnorm, qnorm, rnorm for
normal distribution; dbinom, pbinom, qbinom, rbinom for binomial
distribution).
• Data Manipulation Functions:
o c(...): Combines values into a vector.
o factor(x): Creates a factor.
o sort(x), order(x): Sorts and orders data.
o unique(x): Returns unique elements.
o sample(x, size): Takes a random sample.
o apply(), lapply(), sapply(), tapply(), mapply(): Functions for applying
operations across data structures.
• String Manipulation Functions:
o nchar(x): Returns the number of characters in a string.
o toupper(x), tolower(x): Converts strings to uppercase or lowercase.
o paste(...): Concatenates strings.
o substring(x, first, last): Extracts substrings.
o grep(pattern, x), grepl(pattern, x): Pattern matching.
• Input/Output Functions:
o [Link](), [Link](): Reads data from files.
o [Link](), [Link](): Writes data to files.

A function may explicitly return a value or object (or multiple values or objects) using the
return keyword. If no explicit return statement is included, then the last expression within the
body of the function is returned.

Anatomy Of A Function In R

function_name <- function(parameter1, parameter2, …, parameterN)


{
Statement1
Statement2

StatementN
}

The parameters represent entities that can be passed to the function when it is called or invoked.
The parameter list can be empty and it can contain as many parameters as required. In the
xample above, function_name is the name of the function while parameter1, parameter2,…,
parameterN are parameters.

Default parameters are special parameters that are assigned default values in the function
definition and need not be supplied when the function is actually called or invoked, in which
case the default values are used within the function.

When a function is actually called or invoked, the values or objects passed to the function in
place of the parameters are called arguments.

22
The body of the function is typically enclosed within curly braces and can contain as many
statements as required to perform the task the function is designed to carry out.

Examples

my_function <- function()


{
a <- 3
b <- 5
return (a * b)
}

Call or Invocation

result <- my_function() #Returns 15


print(result) #Prints out 15

sum_of_2_numbers <- function(num1, num2 = 8)


{
return (num1 + num2)
}
sum1 <- sum_of_2_numbers(9, 10) #Returns 19
sum2 <- sum_of_2_numbers(8) #Returns 16, uses default parameter for second argument

Function arguments can be supplied by position or by parameter name.

area_of_triangle <- function(base, height)


{
return ((base / 2) * height)
}

area1 <- area_of_triangle(10, 18) #Returns 90


area2 <- area_of_triangle(height = 18, base = 10) #Returns 90

Inline Functions
These are special functions for which the body is defined directly on a single line without curly
braces.

inline_function <- function(param1, param2) return (param1 * param2)

Functions may be extended within the context of object-oriented programming and in particular
class hierarchies related to inheritance in the R programming language.

23
The Apply Family Of Functions (apply, lapply, sapply, tapply, mapply)

With the apply family of functions, R offers an efficient and concise way to apply a function
to the elements of various data structures, such as matrices, data frames, and lists. This
approach often provides faster execution than traditional for loops. The Apply Family of
functions offers a powerful and efficient way to perform repetitive operations in R, especially
when working with larger datasets.

The main functions in this family include apply(), lapply(), sapply(), tapply(), and mapply().

apply() : Applies a function to the rows or columns of a matrix or data frame.

apply(X, MARGIN, FUN, ...)

X: The input array or matrix.


MARGIN: Specifies whether the function is applied to rows (1), columns (2), or both (c(1,2)).
FUN: The function to be applied (e.g., mean, sum, sd, or a custom function).

my_matrix <- matrix(1:9, nrow = 3)


# Apply sum to each column
col_sums <- apply(my_matrix, 2, sum)
print(col_sums)
# Apply mean to each row
row_means <- apply(my_matrix, 1, mean)
print(row_means)

lapply() : Applies a function to each element of a list and returns a list.

lapply(X, FUN, ...)

X: The input list.


FUN: The function to be applied.

my_list <- list(a = 1:3, b = 4:6, c = 7:9)


# Apply mean to each element of the list
list_means <- lapply(my_list, mean)
print(list_means)

sapply() : Similar to lapply(), but attempts to simplify the output to a vector or matrix if
possible.

sapply(X, FUN, ..., simplify = TRUE, [Link] = TRUE)

X: The input list or vector.


FUN: The function to be applied.
simplify: Logical, whether to simplify the result.

24
my_list <- list(a = 1:3, b = 4:6, c = 7:9)
# Apply mean to each element, simplifying the output to a vector
vector_means <- sapply(my_list, mean)
print(vector_means)

tapply() : Applies a function to subsets of a vector, where the subsets are defined by factors.

tapply(X, INDEX, FUN, ..., simplify = TRUE)

X: The input vector.


INDEX: A factor or list of factors to group the data by.
FUN: The function to be applied.

data_vector <- c(10, 12, 15, 11, 14, 16)


groups <- factor(c("A", "B", "A", "B", "A", "B"))
# Apply mean to data_vector, grouped by 'groups'
group_means <- tapply(data_vector, groups, mean)
print(group_means)

mapply() : Applies a function to corresponding elements of multiple list or vector arguments.


mapply() is considered the multivariate version of sapply().

mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, [Link] = TRUE)

FUN: The function to be applied.


...: The list or vector arguments to which FUN will be applied.
MoreArgs: An optional list of other arguments to FUN that are not to be iterated over (i.e., they
remain constant for each application of FUN).
SIMPLIFY: A logical value indicating whether the result should be simplified to a vector,
matrix, or array if possible.
[Link]: A logical value indicating whether names should be preserved in the output.

# Define a function to add two numbers


add_numbers <- function(x, y)
{
return (x + y)
}

# Create two vectors


vec1 <- c(1, 2, 3)
vec2 <- c(4, 5, 6)

# Use mapply to add corresponding elements


result <- mapply(add_numbers, vec1, vec2)

25
# Print the result
print(result)

Output:
[1] 5 7 9

26
Data Visualization And Reporting In R

R can be used for data visualization to graphically present data in order to enable the acquisition
of actionable insights, a clearer understanding of relationships and to enhance data-driven
decision making.

Basic functions such as plot, barplot, pie, hist (for histograms), and so on, in R can be used for
data visualization and reporting. Additionally, the powerful ggplot2 package can be utilized,
permitting the construction of complex visualizations layer by layer, offering extensive control
over aesthetics, geometries, facets, and themes.
Here, the focus is on the use of the built-in R visualization and reporting features.

Bar Chart In R
Bar charts are used to visually display items in specific categories using bars. The bars can be
vertical or horizontal.

Simple Bar Chart


dataset <- c(25, 5, 15, 30, 50)
barplot(dataset)

Output:

Default Bar Chart

27
Custom Bar Chart
Custom bar charts can be created by supplying custom arguments to the barplot() function.

Dataset <- c(25, 5, 15, 30, 50)


barplot(dataset,
main = “My Custom Bar Chart”, #Title
xlab = “Categories”, #X-axis label
ylab = “Values”, #Y-axis label
[Link] = c(“A”, “B”, “C”, “D”, “E”), #Bar names
col = “blue”, #Bar color
horiz = FALSE) #Vertical bars (Default)

Output:

Custom Bar Chart with bar color set to blue.

28
Pie Chart in R
Pie charts can be used for proportionate representation of items using slices in a circle.

values <- c(15, 30, 45, 10)


labels <-c("Group 1", "Group 2", "Group 3", "Group 4")
colors <- c("blue", "yellow", "green", "red")
pie(values,
labels = labels,
main = "Number of Students In Each Group", #Title
col = colors, #Use custom colors,
clockwise = TRUE) #Draw slices clockwise

Output:

Custom Pie Chart with separate colors and slices for the number of students in each of four (4)
groups.

29
Histogram In R Using In-built Data

Histograms can serve as graphical representations of the density of the underlying distribution
of data. The following example uses built-in data from the R programming language.

data(airquality)

hist(airquality$Temp, main =”La Guardia Airport’s Maximum Temperature(Daily)”,


xlab =”Temperature(Fahrenheit)”,
xlim = c(50, 125), col =”yellow”,
freq = TRUE)

30
Visualize World Map

Visualization of World Map Using Built-in Data

R Source Code: (Acceptance of the list of countries presented and an Internet connection are
required to run this R program)

[Link]("maps")
library(maps)
map(database = "world")

Output:

31
Scatter Plot Using Two R Vectors
Scatter plots can be used to visually represent the correlations between two sets of data.
Example:
x_data <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y_data <- c(2, 4, 5, 4, 6, 7, 8, 9, 10, 12)

Plain plot() Function Call:


plot(x_data, y_data)

Output:

Customized plot() Function Call:


Arguments:
main: Sets the main title of the plot.
xlab, ylab: Sets the labels for the x and y axes, respectively.
col: Changes the color of the points. You can specify a color name (e.g., "red", "blue") or a
numerical index (e.g., 1 for black, 2 for red).
pch: Controls the type of plotting symbol (point). Takes an integer (e.g., 1 for open circle,
16 for filled circle) or a character.
cex: Adjusts the size of the plotting symbols.

32
xlim, ylim: Sets the limits for the x and y axes.

Code:

x_data <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)


y_data <- c(2, 4, 5, 4, 6, 7, 8, 9, 10, 12)

plot(x_data, y_data,
main = "My Custom Scatterplot",
xlab = "X-axis Label",
ylab = "Y-axis Label",
col = "darkred",
pch = 16, # Filled circles
cex = 1.5, # Larger points
xlim = c(0, 12),
ylim = c(0, 15))

Output:

33

You might also like