CW8402 COMPUTATIONAL STATISTICS
OBJECTIVES:
To expose the variables, expressions, control stations of R
To use R Programming for Analysis of data and visualize outcome inform of
graphs, charts
To develop and understand the modern computational statistical approaches
and their applications to different datasets.
To apply principles of data science to analyze various business problems.
To analysis data using various statistical tools like correlation and regression
UNIT I INTRODUCTION TO R
Introduction, History and overview of R, elements and data structures,
Sessions and Functions, Variables, Data Types, Vectors, Scalars, Conclusion,
Data Frames, Lists, Matrices, Arrays, Classes, Data input/output, Data storage
INTRODUCTION TO R
R is one of the most popular analytics tool. But apart from being used for analytics,
R is also a programming language.
With its growth in the IT industry, there is a booming demand for skilled or certified
Data Scientists with an understanding of R as both, a data analytics tool and a
programming language.
History and overview of R
R is a programming language and software environment for
statistical analysis, graphics representation and reporting.
R was initially written by Ross and Robert Gentleman at
the Department of Statistics of the University of Auckland in
Auckland, New Zealand. R made its first appearance in 1993.
The core of R is an interpreted computer language which allows
branching and looping as well as modular programming using
functions.
R allows integration with the procedures written in the C, C+
+, .Net, Python languages for efficiency.
R is freely available under the GNU General Public License, and
pre-compiled binary versions are provided for various operating
systems like Linux, Windows and Mac.
R Vs Python
Installation of R
R programming is a very popular language and to work on that we have to install two
things, i.e., R and RStudio. R and RStudio works together to create a project on R.
Rstudio IDE:
RStudio is an integrated development environment which allows us to interact with R
more readily. RStudio is similar to the standard RGui, but it is considered more user-
friendly. This IDE has various drop-down menus, Windows with multiple tabs, and so
many customization processes.
Elements and data structures
R Programming: Variables
Variables are nothing but a name to a memory location containing a
value. A variable in R can store Numeric values, Complex Values, Words,
Matrices and even a Table.
The above image shows us how variables are created and how they
are stored in different memory blocks.
Let us move forward and try to understand what is a Data type and
the various Data types supported in R.
R Data Types
Five Data Types/Structures of R
1. Vector
When you want to create vector with more than one element, you should
use c() function which means to combine the elements into a vector.
Logical: It is used to store logical value like TRUE or FALSE.
Integer: It holds all the integer values i.e. all the positive and negative whole numbers.
(Because R's integers are 32-bit long integers and "L" therefore appears to be sensible
shorthand for referring to this data type.)
Eg: 25L, -35L,65L
Numeric: It is used to store both positive and negative numbers including real number.
Eg: 25, 7.1145 , 96547
Character: It is used to store either a single character, group of characters(words) or a
group of words together. The characters may be defined in either single quotes or double
quotes.
Eg: "Edureka", 'R is Fun to learn'.
Complex: These are of the form x + yi, where x and y are numeric and i represents the
square root.
Eg: 4+3i
Example
Example
•The c function in R programming stands for 'combine. ‘
• This function is used to get the output by giving parameters inside the function.
2. Matrix Data Type
Matrix is the R object in which the elements are arranged
in a two-dimensional rectangular layout.
The basic syntax for creating a matrix in R is −
matrix(data, nrow, ncol, byrow, dimnames)
Where:
data is the input vector which becomes the data elements
of the matrix.
nrow is the number of rows to be created.
ncol is the number of columns to be created.
byrow is a logical clue. If TRUE, then the input vector
elements are arranged by row.
dimname is the names assigned to the rows and columns.
Example
Mymatrix = matrix(c(1:25), nrow = 5, ncol = 5, byrow = TRUE)
Mymatrix
Output:
[Link] in R
Array Example
Array Example
Naming of Array in R
In R, we can give the names to the rows, columns, and
matrices of the array. This is done with the help of the
dimname parameter of the array() function.
The row names, column names and matrices names are
specified as a vector of the number of rows, number of
columns and number of matrices respectively.
By default, the rows, columns and matrices are named by
their index values.
Below is an example, in which we create two arrays and
Example
Let's take an example below where the array
contains vector input from 1 to 9.
There are only three rows and columns where the
value is from 1 to 9 is included.
The '[Link]' is the new column name which
have vectors ('c1', 'c2', 'c3') and '[Link]' is the
new row names ('r1', 'r2', 'r3') which is also the
vector.
Naming in R Array Example
Example:
• a1= c (1,2,3,4)
• a2= c (5,6,7,8,9)
• [Link] = c ("c1","c2","c3")
• [Link] = c ("r1","r2","r3")
• [Link] = c ("first")
• arr = array (c (a1,a2), dim=c (3,3,1), dimnames=list ([Link], [Link], [Link]))
• print(arr)
The output of the above code is below:
, , first
c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9
Naming Columns and Rows in R Array
Accessing Array Element
Like C or C++, we can access the elements of the array.
The elements are accessed with the help of the index.
Simply, we can access the elements of the array with the help
of the indexing method.
Indexing in an array
An array consists of elements in a multi-dimensional
manner where each element can be accessed for the
operation.
The elements can be indexed by using '[]' wherein the array-
like matrices consists of rows and columns which can be
indexed by: mat[row, column]
Example
a1= c (1,2,3,4)
a2= c (5,6,7,8,9)
[Link] = c ("c1","c2","c3")
[Link] = c ("r1","r2","r3")
[Link] = c ("first") arr = array (c (a1,a2), dim=c (3,3,1), dimnames=list ([Link], [Link],
[Link]))
print(arr)
Output:
, , first
## You can see the matrices from 1 to 9 are generated with 3 3 dimension(row column)
c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9
1. Let's extract number '7' from the above array 'arr'.
arr[1,3,1]
7
The output to the above code is [Link] of 'arr[1,3,1]' row 1 with column 3 and 1 is the first array
c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9
2. To access first element
Row one, column one and first array element is extracted.
arr[1,1,1]
1
3. To access multiple values at once, you need to specify the range you
want.
arr[1:2,1]
The above code gives the output as below where the value containing 2
rows, 2 columns and 1 is the first array 'arr' is extracted:
c1 c2
r1 1 4
c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9
[Link] can get the entire second row by following code where
arr[2, ,1] gets the second row with space, and 1 is the 'arr' to be
extracted.
arr[2, ,1]
258
5. To access the entire array with the following syntax .
arr[ , ,1]
c1 c2 c3
R 1 4 7
R 2 5 8
R 3 6 9
6. Matrix Creation and Addition (or) Manipulation of elements
Let's create a matrix named mat1 and mat2 from 'arr[ , ,1]' where the entire rows and
columns from 'arr' get copied.
mat1 = arr[,,1]
mat2 = arr[,,1]
final = mat1+mat2
print(final)
Output:
c1 c2 c3
r1 2 8 14
r2 4 10 16
r3 6 12 18
In Example given below:
We use the apply() function below to calculate the sum of the elements in the rows of
an array across all the matrices.
Example for Calculations Across Array Elements
# Create two vectors of different lengths.
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
# Take these vectors as input to the array.
[Link] <- array(c(vector1,vector2),dim = c(3,3,2))
print([Link])
# Use apply to calculate the sum of the rows across all the matrices.
result <- apply([Link], c(1), sum)
print(result)
Output: ,,2
$Rscript main.r
,,1 [,1] [,2] [,3]
[1,] 5 10 13
[,1] [,2] [,3] [2,] 9 11 14
[1,] 5 10 13 [3,] 3 12 15
[2,] 9 11 14
[3,] 3 12 15 [1] 56 68 60
Summary of Array in R
4. List in R
Lists are the R objects which contain elements of different types like − numbers,
strings, vectors and another list inside it.
A list can also contain a matrix or a function as its elements. List is created
using list() function.
List
Lists are quite similar to vectors, but Lists are the R objects which can contain
elements of different types like − numbers, strings, vectors and another list inside it.
1. Creating a List
Following is an example to create a list containing strings, numbers, vectors and a
logical values.
# Create a list containing strings, numbers, vectors and a logical values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)
2. Naming List Elements:
The list elements can be given names and they can be accessed using these names.
# Create a list containing a vector, a matrix and a list.
list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
# Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
# Show the list.
print(list_data)
2. Accessing List Elements:
Elements of the list can be accessed by the index of the element in the list. In case of
named lists it can also be accessed using the names.
We continue to use the list in the above example
3. Merging Lists
You can merge many lists into one list by placing all the lists
inside one list() function.
4.R Programming Manipulating List Elements:
We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list.
But we can update any element.
5. Converting List to Vector:
A list can be converted to a vector so that the elements of the vector
can be used for further manipulation. All the arithmetic operations on
vectors can be applied after the list is converted into vectors. To do this
conversion, we use the unlist() function. It takes the list as input and
produces a vector.
[Link] Frames in R
A data frame is a table or a two-dimensional array-
like structure in which each column contains values of
one variable and each row contains one set of values
from each column.
Following are the characteristics of a data frame.
The column names should be non-empty.
The row names should be unique.
The data stored in a data frame can be of numeric,
factor or character type.
Each column should contain same number of data
items.
Example of Data Frame
strings are read by default as factors (i.e.
distinct groups). This has two consequences:
Your data is stored more efficiently, because
each unique string gets a number and
whenever it's used in your data frame you
can store its numerical value (which is much
smaller in size)
Summary of Data in Data Frame
The statistical summary and nature of the data can be obtained by
applying summary() function.
•Mean – Average
•Median - Situated in the middle
•The first quartile 25% .
•The third quartile 75%.
Summary of Data in Data Frame
Mean – Average
Median - Situated in the middle
The first quartile, or lower quartile, is the value that cuts
off the first 25% of the data when it is sorted in ascending
order.
The second quartile, or median, is the value that cuts off
the first 50%.
The third quartile, or upper quartile, is the value that
cuts off the first 75%.
Add Rows in Data Frame
To add more rows permanently to an existing data frame, we need to bring in the new rows in
the same structure as the existing data frame and use the rbind() function.
Add Columns in Data Frame
Use the cbind() function to add new columns in a Data Frame
R Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Built In-Functions
Simple examples of in-built functions are seq(), mean(), max(), sum(x) etc.
They are directly called by user written programs. You can refer most widely used R
functions.
Creating a Functions
An R function is created by using the keyword function. The basic
syntax of an R function definition is as follows
Call a Function
To call a function, use the function name followed by parenthesis,
like my_function():
Parameter & Argument Passing Inside Functions
The terms "parameter" and "argument" can be used for the
same thing: information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in
the function definition.
An argument is the value that is sent to the function when it
is called.
Example
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.
Objects and Classes in R
Classes and Objects are basic concepts of Object-Oriented
Programming that revolve around the real-life entities. Everything in R is
an object.
An object is simply a data structure that has some methods and
attributes.
A class is just a blueprint or a sketch of these objects. It represents the
set of properties or methods that are common to all objects of one type.
Unlike most other programming languages, R has a two-class system.
They are S3, S4 Classes.
S3 Class
With the help of the S3 class, we can take advantage of the ability to implement the
generic function OO. Furthermore, using only the first argument, S3 is capable of
dispatching.
Creating an S3 class:
In R, we define a function which will create a class and return the object of the
created class. A list is made with relevant members, class of the list is determined, and
a copy of the list is returned. There is the following syntax to create a class.
S4 Class
S4 is a slight improvement over S3 as its objects have a proper definition and it gives
a proper structure to its objects.
Creating an S4 class
In R, we use setClass() command for creating S4 class. In S4 class, we will specify a
function for verifying the data consistency and also specify the default value. In R,
member variables are called slots.
Data Input & Output
Developers often have a need to interact with users,
either to get data or to provide some sort of result.
Most programs today use a dialog box as a way of
asking the user to provide some type of input.
Like other programming languages in R it’s also
possible to take input from the user.
For doing so, there are two methods in R.
Using readline() method
Using scan() method
Using readline() method
In R language readline() method takes input in string format.
If one inputs an integer then it is inputted as a string, lets say,
one wants to input 255, then it will input as “255”, like a string.
So one needs to convert that inputted value to the format that
he needs. In this case, string “255” is converted to integer 255.
To convert the inputted value to the desired data type, there
are some functions in R they are.
[Link](n); —> convert to integer
[Link](n); —> convert to numeric type (float, double etc)
[Link](n); —> convert to complex number (i.e 3+2i)
[Link](n) —> convert to date …, etc
Example readline()
Using scan() method
Another way to take user input in R language is using
a method, called scan() method. This method takes
input from the console.
This method is a very handy method while inputs are
needed to taken quickly for any mathematical
calculation or for any dataset.
This method reads data in the form of a vector or list.
This method also uses to reads input from a file also.
Example Scan()
Print output using print() function
Using print() function to print output is the most common method in R.
Implementation of this method is very simple.
Data Storage Formats
These extensions are conventional rather than
mandatory.
The workspace stored in the working directory for R
implementations is called ".
“Rdata” and is normally hidden following operating
system conventions for filenames beginning with
periods.
Subsetting objects
Using the ‘[ ]’ operator, elements of vectors and observations from data frames can
be accessed.
To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data
frame.
Subsetting Example
In this example, let us use mtcars data frame present in R base package for
subsetting.
[Link]
Data Analysis
• Import Xl data
• Slice Operation
• Hist,plot,lines - plot(testdata$Rank)
Vectorization
Most of R's functions are vectorized, meaning that the
function will operate on all elements of a vector
without needing to loop through and act on each
element one at a time.
This makes writing code more concise, easy to read,
and less error prone.
END OF UNIT-1