Programming in R
Programming in R
1
Introduction
•R is a popular programming language used for statistical computing and
graphical presentation.
•Its most common use is to analyze and visualize data.
•It is easy to draw graphs in R, like pie charts, histograms, box plot, scatter plot,
etc++
•It works on different platforms (Windows, Mac, Linux)
•It is open-source and free
•It has a large community support
•It has many packages (libraries of functions) that can be used to solve different
problems.
2
R Variables
A variable is a memory allocated for the storage of specific data and the
name associated with the variable is used to work around this reserved
block.
Syntax
5
1. Nominal Attributes :
• Nominal attributes, as related to names, refer to categorical data where the values
represent different categories or labels without any inherent order or ranking.
• These attributes are often used to represent names or labels associated with objects,
entities, or concepts.
6
Binary Attributes:
• Binary attributes are a type of qualitative attribute where the data can take on only two distinct values
or states.
• These attributes are often used to represent yes/no, presence/absence, or true/false conditions within a
dataset.
Symmetric:
• In a symmetric attribute, both values or states are considered equally important or
interchangeable.
Asymmetric:
• An asymmetric attribute indicates that the two values or states are not equally important or
interchangeable.
• For instance, in the attribute “Result” with values “Pass” and “Fail,” the states are not of equal
importance; passing may hold greater significance than failing in certain contexts, such as academic
grading or certification exams
•
7
Ordinal Attributes :
• Ordinal attributes are a type of qualitative attribute where the values possess a meaningful order or ranking, but the
magnitude between values is not precisely quantified.
• In other words, while the order of values indicates their relative importance or precedence, the numerical difference
between them is not standardized or known.
Example:
. Numeric:
A numeric attribute is quantitative because, it is a measurable quantity,
•interval-scaled attribute has values, whose differences are interpretable, but the numerical attributes do not have the
correct reference point, or we can call zero points.
•Example:Temprature
• ratio-scaled attribute is a numeric attribute with a fix zero-point. If a measurement is ratio-scaled, we can say of a
value as being a multiple (or ratio) of another value.
• The values are ordered, and we can also compute the difference between values, and the mean, median, mode,
Quantile-range, and Five number summary can be given.
8
Attributes
9
Numeric, Character, and Logical Data Types
10
Numeric, Character, and Logical Data Types
11
Data Structures
in R
12
The most essential data structures used in R include:
•Scalers
•Vectors
•Lists
•Dataframes
•Matrices
•Arrays
•Factors
13
14
15
Vectors
Vector is one of the basic data structures in R. It is homogenous, which
means that it only contains elements of the same data type. Data types can be
numeric, integer, character, complex, or logical.
Example
# Vectors(ordered collection of same data type)
X = c(1, 3, 5, 7, 8)
# Printing those elements in console
print(X)
Output
[1] 1 3 5 7 8 16
Lists
A list is a non-homogeneous data structure, which implies that it can contain
elements of different data types. It accepts numbers, characters, lists, and even
matrices and functions inside it. It is created by using the list() function.
Example
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(empId, empName, numberOfEmp)
print(empList)
Output
[[1]] [1] 1 2 3 4
[[2]] [1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]] [1] 4
17
Matrices
A matrix is a rectangular arrangement of numbers in rows and columns. In a
matrix, as we know rows are the ones that run horizontally and columns are the
ones that run vertically. Matrices are two-dimensional, homogeneous data
structures.
Example
M1 <- matrix(c(1:9), nrow = 3, ncol =3, byrow= TRUE)
print(M1)
Output
[,1] [,2] [,3]
[,1] 1 2 3
[,2] 4 5 6
[,3] 7 8 9 18
19
20
21
22
23
Arrays
Arrays refer to the type of data structure that is used to store multiple items of
a similar type together. This leads to a collection of items that are stored at
contiguous memory locations. This memory location is denoted by the array name.
The position of an element can be calculated simply by adding an offset to its base
value.
Example
Array Structure
An array consists of the following:
Array Index: The array index identifies the location of the element. The array index
starts with 0.
Array Element: Array elements are items that are stored in the array.
Array Length: The array length is determined by the number of elements that can
be stored by the array.
24
There are two types of arrays:
•One-dimensional Arrays
•Multi-dimensional Arrays
•One-dimensional Arrays
One- or single-dimensional arrays are the types of arrays that have array elements
stored in a sequence and can be accessed in the same order.
Multi-dimensional Arrays
Multi-dimensional arrays are arrays that have elements stored in more than one
dimension. They can be two- or three-dimensional arrays and can consist of row
and column indexes.
To create an array in R:
The array() function is utilised.
In this function, the input is a vector.
For creating the array, the value in the dim parameter is utilised.
25
For example:
In this following example, we will create an array in R of two 3×3 matrices
each with 3 rows and 3 columns.
26
Output
27
Data Frames
A data frame is a two-dimensional array-like structure, or we can say it is a table
in which each column contains the value of one variable, and row contains the
set of value from each column.
There are the following characteristics of a data frame:
•The column name will be non-empty.
•The row names will be unique.
•A data frame stores numeric, factor or character type data.
•Each column will contain same number of data items.
To create a data frame we use the [Link]() function.
28
R program to illustrate dataframe
# A vector which is a character vector
Name = c("Amiya", "Raj", "Asish")
print(df) 29
R Data Frames Structure
Get the Structure of the R Data Frame
One can get the structure of the R data frame using str() function in R.
Summary of Data in the R data frame
Extract Data from Data Frame in R
Expand Data Frame in R Language
Remove Rows and Columns
Factors
● Factors are also data objects that are used to categorize the data and store
it as levels.
● Factors can store both strings and integers.
● Columns have a limited number of unique values so that factors are very
useful in columns.
● It is very useful in data analysis for statistical modeling.
Factors are created with the help of factor() function by taking a vector as an
input parameter.
36
Example
38
Strings in R
A string is a sequence of characters. For example, "Programming" is a string that
includes characters: P, r, o, g, r, a, m, m, i, n, g.
In R, we represent strings using quotation marks (double quotes, " " or single
quotes, ' ').
For example
# string value using single quotes
'Hello‘
# string value using double quotes
"Hello"
Example: Strings in R
message1 <- 'Hola Amigos' print(message1)
message2 <- "Welcome to Programiz" print(message2)
Output
[1] "Hola Amigos“
39
[1] "Welcome to Programiz"
Example
Output
[1] ‘Start and end with single quote’
[1] "Start and end with double quotes“
[1] "single quote ' in between double quote"
40
[1] ‘Double quote " in between single quote"
Join Strings Together
In R, we can use the paste() function to join two or more strings together.
For example
message1 <- "Programiz" message2 <- "Pro" # use paste() to join two strings
paste(message1, message2)
Output
[1] Programiz Pro
Example
message1 <- "Hello, World!"
message2 <- "Hola, Mundo!“
message3 <- "Hello, World!“
# compare message1 and message2 print(message1 == message2)
# compare message1 and message3 print(message1 == message3)
Output
[1] FALSE
[1] TRUE 41
R Looping
● Loops are used to repeat the process until the expression (condition) is TRUE. R
uses three keywords for, while and repeat for looping purpose. Next and break,
provide additional control over the loop.
● The break statement exits the control from the innermost loop. The next statement
immediately transfers control to return to the start of the loop and statement after
next is skipped.
● The value returned by a loop statement is always NULL and is returned invisibly.
There are three types of loops in R programming:
•For Loop
•While Loop
•Repeat Loop 42
For Loop in R
44
Example 1: Program to display numbers from 1 to 5 using for loop in R
fruits<-list("apple","banana","cherry")
for(x in fruits)
{
print(x)
}
Output
[1] “apple”
[1] “banana”
[1] “cherry” anana"
[1] "cherry«[1]{ 45
While Loop in R
● It is a type of control statement that will run a statement or a set of statements repeatedly
unless the given condition becomes false.
● It is also an entry-controlled loop, in this loop, the test condition is tested first, then the
body of the loop is executed, the loop body would not be executed if the test condition is
false.
Syntax:
while (expression)
{
statement
} 46
Flow Diagram:
47
Example: Print i as long as i is less than 6
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
Output
[ 1[[
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5 48
[1] 4
Repeat loop
● A repeat loop is used to iterate a block of code.
● It is a special type of loop in which there is no condition to exit from the loop.
● For exiting, we include a break statement with a user-defined condition.
● This property of the loop makes it different from the other loops.
● A repeat loop constructs with the help of the repeat keyword in R.
● It is very easy to construct an infinite loop in R.
Syntax:
repeat {
commands
if(condition) {
break } }
49
Flow Diagram:
50
Example
v <- c("Hello","repeat","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5)
{
break
}
}
51
Output:
52
Data Import and Export
Data Import
Reading a Comma-Separated Value(CSV) File
data1
Data Import
Method 2: Using [Link]() Function
This function specifies how the dataset is separated, in this case we take sep="/t " as an argument.
data2
Data Import
Reading a Tab-Delimited(txt) File
Tab-delimited files are commonly used for data exchange and R supports reading them with built-in methods.
data3
Method 2: Using [Link]() Function
This function specifies how the dataset is separated, in this case we take sep="\t" as the argument.
data4
57
Data Import
65
Process of Descriptive Statistics in R
● The measure of central tendency
● Measure of variability
66
Measure of central tendency
It represents the whole set of data by a single value. It gives us the location of central points. There are three
main measures of central tendency:
● Mean
● Mode
● Median
67
Measure of variability
In Descriptive statistics in R measure of variability is known as the spread of data or how well is our data is
distributed. The most common variability measures are:
● Range
● Variance
● Standard deviation
68
Descriptive Analysis in R
• Descriptive analyses consist of describing simply the data using some summary statistics
and graphics
# Descriptive Analysis
myData = [Link]("[Link]",
stringsAsFactors = F)
69
70
Data visualization with R and ggplot2
• The ggplot2 ( Grammar of Graphics ) is a free, open-source visualization package widely used in R
Programming Language.
• It includes several layers on which it is governed. The layers are as follows:
• Data: The element is the data set itself.
• Aesthetics: The data is to map onto the Aesthetics attributes such as x-axis, y-axis, color, fill, size,
labels, alpha, shape, line width, line type.
• Geometrics: How our data being displayed using point, line, histogram, bar, boxplot.
• Facets: It displays the subset of the data using Columns and rows.
• Statistics: Binning, smoothing, descriptive, intermediate.
• Coordinates: the space between data and display using Cartesian, fixed, polar, limits.
• Themes: Non-data link.
71
72
mtcars(motor trend car road test) dataset
73
1. Data Layer
The data layer we define the source of the information to be visualize, let’s use the mtcars dataset in the ggplot2
package.
library(ggplot2)
library(dplyr)
74
2. Aesthetic Layer
75
3. Geometric layer
The geometric layer control the essential elements, see how our data being displayed using point, line, histogram, bar, boxplot.
76
# Adding size
ggplot(data = mtcars, aes(x = hp, y = mpg, size = disp)) +
geom_point() +
labs(title = "Miles per Gallon vs Horsepower",
x = "Horsepower",
y = "Miles per Gallon")
# Histogram plot
ggplot(data = mtcars, aes(x = hp)) +
geom_histogram(binwidth = 5) +
labs(title = "Histogram of Horsepower",
x = "Horsepower",
y = "Count")
77
78
4. Facet Layer
● The facet layer is used to split the data up into subsets of the entire dataset and it
allows the subsets to be visualized on the same plot.
p + facet_grid(am ~ .) +
labs(title = "Miles per Gallon vs Horsepower",
x = "Horsepower",
y = "Miles per Gallon")
p + facet_grid(. ~ cyl) +
labs(title = "Miles per Gallon vs Horsepower",
x = "Horsepower",
y = "Miles per Gallon")
79
5. Statistics layer
This layer transforms our data using binning, smoothing, descriptive, intermediate summaries.
80
6. Coordinates layer
In these layers, data coordinates are mapped together to the mentioned plane of the graphic and we adjust the axis and
changes the spacing of displayed data with Control plot dimensions.
81
7. Theme Layer
This layer controls the finer points of display like the font size and background color properties.
82
Histogram of Age Distribution
library(ggplot2)
ggplot(myData, aes(x = Age)) +
geom_histogram(binwidth = 2, fill = "blue", color = "red", alpha = 0.8) +
labs(title = "Age Distribution", x = "Age", y = "Frequency")
bar chart illustrating the distribution of 'Education' levels from the 'myData' 85
dataset
Mean
It is the sum of observations divided by the total number of observations. It is also defined as average
which is the sum divided by count.
# R program to illustrate
# Descriptive Analysis
86
Median
It is the middle value of the data set. It splits the data into two halves. If the number of elements in the data set is odd then the
center element is median and if it is even then the median would be the average of two central elements.
# R program to illustrate
# Descriptive Analysis
87
Mode
It is the value that has the highest frequency in the given data set. The data set may have no mode if the frequency of all data
points is the same. Also, we can have more than one mode if we encounter two or more data points having the same frequency.
# R program to illustrate
# Descriptive Analysis
88
Range
The range describes the difference between the largest and smallest data point in our data set. The bigger the range, the more is the
spread of data and vice versa.
# R program to illustrate
# Descriptive Analysis
It is defined as an average squared deviation from the mean. It is being calculated by finding the difference
between every data point and the average which is also known as the mean, squaring them, adding all of them,
and then dividing by the number of data points present in our data set.
# R program to illustrate
# Descriptive Analysis
# Calculating variance
variance = var(myData$Age)
print(variance)
90
Standard Deviation
It is defined as the square root of the variance. It is being calculated by finding the Mean, then subtract each number from the
Mean which is also known as average and square the result. Adding all the values and then divide by the no of terms followed the
square root.
# R program to illustrate
# Descriptive Analysis
91
Exploratory Data Analysis in R Programming
● Exploratory Data Analysis (EDA) is a process for analyzing and summarizing the key characteristics of a dataset,
often using visual methods.
● It helps to understand the structure, relationships and potential issues in data before conducting formal modeling.
1. Descriptive Statistics: Summarizing data using numerical methods such as mean, median and standard deviation.
2. Graphical Methods: Visualizing data through plots like histograms, box plots and scatter plots.
In this example, we will use the built-in iris dataset in R to show EDA techniques.
data("iris")
head(iris)
93
1. Descriptive Statistics for EDA
● Descriptive statistics involve summarizing and describing the main features of a dataset through
numerical measures like mean, median, mode, standard deviation, variance and range.
● These statistics help in understanding the central tendency, dispersion and overall distribution of
the data
94
1.1 Measures of Central Tendency
95
1.2 Measures of Dispersion
96
1.3 Correlation
Next, we examine the relationships between numerical variables by computing the correlation matrix.
● corr(): Computes the correlation matrix for a set of numeric variables, showing relationships between
them.
cor(iris[, 1:4])
97
2. Graphical Methods for EDA
● Graphical methods involve visualizing the data using plots such as histograms, box plots, scatter plots and bar charts.
● These visualizations help in identifying patterns, trends, outliers and the distribution of data, making it easier to
interpret and communicate insights.
We begin by plotting histograms to visualize the distribution of variables like Sepal Length.
● ggplot(): Initializes a plot object in ggplot2, taking data and aesthetic mappings.
● geom_histogram(): Creates a histogram to visualize the distribution of a variable.
[Link]("ggplot2")
library(ggplot2)
98
Next, we can plot the density curve for Sepal Length:
● geom_density(): Plots a smooth curve (kernel density estimate) to show the distribution of a continuous variable.
99
2.2 Box Plot
A box plot is useful to visualize the spread and potential outliers in the data.
100
2.3 Scatter Plot
We can also examine the relationships between two numerical variables with scatter plots. For example, we’ll plot Sepal
Length against Sepal Width.
● geom_point(): Creates a scatter plot to show the relationship between two variables.
101
2.4 Pairwise Plot
For more comprehensive visualization, a pairwise scatter plot (or pairs plot) can help us see all pairwise relationships
between the numerical variables in the dataset.
102
Dirty Data
• Dirty data refers to data that is inaccurate, incomplete, inconsistent, or contains
errors, making it challenging to use for analysis or decision-making.
• Dirty data can be a result of various factors, including human error, data entry
mistakes, software bugs, hardware malfunctions, or problems during data
migration and integration
103
There are Several Types of Dirty Data:
1. Missing values: Some records may lack certain attributes, leaving gaps in the dataset.
2. Inconsistent data: Inconsistencies occur when the same data element is recorded differently across
various parts of the dataset.
3. Duplicate data: The same information is recorded multiple times, leading to redundant entries.
4. Outliers: These extreme values deviate significantly from the rest of the data, potentially skewing
analysis results.
5. Incorrect data: Data may be wrongly entered, outdated, or poorly validated.
6. Non-standardised data: Differences in formatting and units of measurement can lead to confusion
and errors during analysis.
104
What Causes Dirty Data?
Dirty data can be caused by various factors, both human and technological. Some of the common reasons for dirty data
include:
1. Data Entry Errors: Human errors during manual data entry can lead to typos, misspellings, and incorrect data being
recorded.
2. Software Bugs: Errors in data collection and storage software can introduce inaccuracies into the dataset.
3. Lack of Validation: When data is not properly validated during data entry, it increases the likelihood of incorrect or
invalid information being included.
4. Data Integration and Migration: During the process of integrating data from multiple sources or migrating data
between systems, errors can occur, leading to inconsistencies and data quality issues.
5. Inadequate Data Cleaning: If data cleaning and preprocessing steps are not performed properly or skipped
altogether, dirty data can persist in the dataset.
105
6. Outdated Information: Data can become dirty if it's not regularly updated and becomes obsolete over time.
7. Duplicate Records: Poor data management practices or system errors can result in the creation of duplicate records.
8. Non-Standardised Data: Inconsistent formatting, units of measurement, or naming conventions can introduce confusion
and errors in the dataset.
9. External Factors: Sometimes, external events or circumstances can influence data quality, such as natural disasters, power
outages, or cyber-attacks.
10. Data Privacy Issues: When individuals provide inaccurate information or intentionally misrepresent themselves to
protect their privacy, it can lead to dirty data.
11. Sensor or Instrument Malfunctions: In IoT (Internet of Things) applications, malfunctioning sensors or instruments can
generate inaccurate data.
106
Visualizing a single variable
Visualizing a single variable in R depends on whether the data is categorical (discrete groups) or
numerical (continuous values).
107
108
Multivariate-data-visualization
• In this method, graphs and charts are made to show how the various factors
data.
109
● Scatterplots: In multivariate data visualization, scatterplots can be used to visualize the
relationship between multiple variables by coloring the points or adding shapes or sizes.
● Line Graphs: In multivariate data visualization, Line graphs can be used to compare the trends
of two variables or to show the trends of several variables across time.
● Bar Charts: In multivariate data visualization, By stacking or grouping the bars, bar charts can
be used to compare the values of several category variables.
● Heatmaps: Heatmaps are a type of plot used to display the relationship between multiple
variables. Heatmaps use colors to represent the values of the variables, and rows and columns
represent the different variables.
● Boxplots: In multivariate data visualization, the distributions of a continuous variable over
various categories can be compared using boxplots.
● Correlation Matrix: In multivariate data visualization, to see the connections between
variables, a heatmap or other graphical display can be used to visualize a correlation matrix.
110
Multivariate-data-visualization
• Scatterplot Matrix
111
Multivariate-data-visualization
• Parallel Coordinate Plot
• Bubble Chart
112