Lab Book of Data Analysis Using R Programming
Lab Book of Data Analysis Using R Programming
) Semester-V
(NEP 2020 Pattern)
Student Name:
College Name:
Academic Year:
CERTIFICATE
Please read the following instructions carefully and follow them during practical.
• Students are expected to carry this workbook every time they come to the lab for
computer practical.
• Students should prepare for the assignment by reading the relevant material which is
mentioned in ready reference and the concepts taught in class.
• Instructor will specify which problems to solve in the lab during the allotted slot and
student should complete them and get verified by the instructor. However, student
should spend additional hours in Lab and at home to cover all workbook assignments if
needed.
• Students will be assessed for each exercise on a scale from 0 to 5.
Notdone 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
WellDone 5
You have to ensure appropriate hardware and software is made available to each
student.
The operating system and software RStudio
Data Analysis Using R Programming
Sr. No. Assignment Name Marks Teacher’s
(out of 5) Sign
1 Basic R Programming
7
Data Analysis
8
Data Visualization
Total ( Out of 40 )
Total (Out of 5)
Assignment 1: Basic R Programming
Introduction:
R is a programming language and software environment for statistical analysis, graphics
representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the
University of Auckland, New Zealand, and is currently developed by the R Development Core
Team.
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 or FORTRAN languages for efficiency.
Install R on windows
1
Step – 5: Run the .exe file and follow the installation instructions.
2
5.c. Select the components you wish to install (it is recommended to install all the components).
Click Next.
5.d. Enter/browse the folder/path you wish to install R into and then confirm by clicking Next.
5.e. Select additional tasks like creating desktop shortcuts etc. then click Next.
3
5.f. Wait for the installation process to complete.
4
Install RStudio on Windows:
Step – 1: With R-base installed, let’s move on to installing RStudio. To begin, go to download
RStudio and click on the download button for RStudio desktop.
Step – 2: Click on the link for the windows version of RStudio and save the .exe file.
Step – 3: Run the .exe and follow the installation instructions.
1.b. Enter/browse the path to the installation folder and click Next to proceed.
5
1.c. Select the folder for the start menu shortcut or click on do not create shortcuts and then
click Next.
6
1.e. Click Finish to end the installation.
Data Types:
1. Logical:
It is a special data type for data with only two possible values which can be construed
as true/false.
Example:
True, False
2. Numeric:
Decimal value is called numeric in R, and it is the default computational data types.
Example:
12,32,112,5432
7
3. Integer:
Here, L tells R to store the value as an integer
Example:
3L, 66L, 2346L
4. Complex:
A complex value in R is defined as the pure imaginary value i.
Example:
Z=1+2i, t=7+3i
5. Character
In R programming, a character is used to represent string values. We convert objects
into character values with the help [Link]() function.
Example:
'a', '"good'", "TRUE", '35.4'
Variables in R:
Variables are used to store the information to be manipulated and referenced in the R
program. The R variable can store an atomic vector, a group of atomic vectors, or a combination
of many R objects.
A valid variable name consists of letters, numbers and the dot or underline characters.
The variable name starts with a letter or the dot not followed by a number.
Example:
Var.1 = c(0,1,2,3)
Operators in R programming:
Operators Description
Arithmetic Operators() + Adds two vectors
- Subtracts second vector from the first
* Multiplies both vectors
/ Divide the first vector with the second
%% Give the remainder of the first vector with the
second
%/% The result of division of first vector with second
(quotient)
^ The first vector raised to the exponent of second
8
vector
Relational Operators > Checks if each element of the first vector is greater
than the corresponding element of the second
vector
< Checks if each element of the first vector is less
than the corresponding element of the second
vector.
== Checks if each element of the first vector is equal to
the corresponding element of the second vector.
<= Checks if each element of the first vector is less
than or equal to the corresponding element of the
second vector.
>= Checks if each element of the first vector is greater
than or equal to the corresponding element of the
second vector.
Practice Programs:
1. Write a R program to take input from the user (name and age) and display the values.
Also print the version of R installation.
2. Write a R program to get the details of the objects in memory.
SET A:
9
1. Write a R program to accept dimensions of a cylinder and print the surface area and
volume.
2. Write a R program to accept temperatures in Fahrenheit (F) and print it in Celsius(C) and
Kelvin (K).
3. Write a R program to accept two numbers and print arithmetic and harmonic mean of the
two number.
4. Accept three dimensions length (l), breadth(b) and height(h) of a cuboid and print surface
area and volume
SET B:
1. Accept the x and y coordinates of two points and computes the distance between the two
points.
2. A cashier has currency notes of denomination 1, 5 and 10. Accept the amount to be
withdrawn from the user and print the total number of currency notes of each denomination
the cashier will have to give.
SET C:
1. Write a R program to create a sequence of numbers from 20 to 50 and find the mean of
numbers from 20 to 60 and sum of numbers from 51 to 91.
Assignment Evaluation
Signature of Instructor
10
Assignment 2: Decision making and loop control structures
if Statement:
The if statement consists of the Boolean expressions followed by one or more statements.
The if statement is the simplest decision-making statement which helps us to take a decision on
the basis of the condition.
The if statement is a conditional programming statement which performs the function and
displays the information if it is proved true.
if(boolean_expression) {
// If the boolean expression is true, then statement(s) will be executed.
}
Flow Chart:
Example:
x <- 5
if(x > 0){
print("Positive number")
11
}
Output
[1] "Positive number"
If-else statement:
In the if statement, the inner code is executed when the condition is true. The code which
is outside the if block will be executed when the if condition is false.
There is another type of decision-making statement known as the if-else statement. An if-
else statement is the if statement followed by an else statement. An if-else statement, else statement
will be executed when the boolean expression will false. In simple words, If a Boolean expression
will have true value, then the if block gets executed otherwise, the else block will get executed.
The basic syntax of If-else statement is as follows:
if(boolean_expression) {
// statement(s) will be executed if the boolean expression is true.
} else {
// statement(s) will be executed if the boolean expression is false.
}
Flow Chart:
12
Example:
x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}
Output:
[1] "Negative number"
Switch Statement:
A switch statement is a selection control mechanism that allows the value of an expression
to change the control flow of program execution via map and search.
The switch statement is used in place of long if statements which compare a variable with
several integral values. It is a multi-way branch statement which provides an easy way to dispatch
execution for different parts of code. This code is based on the value of the expression.
Flow Chart:
13
next Statement:
The next statement is used to skip any remaining statements in the loop and continue
executing. In simple words, a next statement is a statement which skips the current iteration of a
loop without terminating it. When the next statement is encountered, the R parser skips further
evaluation and starts the next iteration of the loop.
Syntax
next
Flowchart
Example:
x <- 1:5
for (val in x) {
if (val == 3){
next
}
print(val)
}
Output:
[1] 1
[1] 2
[1] 4
[1] 5
14
Break Statement:
The break statement is used to break the execution and for an immediate exit from the loop.
In nested loops, break exits from the innermost loop only and control transfer to the outer loop.
It is useful to manage and control the program execution flow. We can use it to various
loops like: for, repeat, etc.
Syntax:
Break
Flowchart:
Example:
x <- 1:5
for (val in x) {
if (val == 3){
break
}
print(val)
}
15
Output:
[1] 1
[1] 2
Loops:
The function of a looping statement is to execute a block of code, several times and to
provide various control structures that allow for more complicated execution paths than a usual
sequential execution.
Repeat Loop:
A repeat loop is one of the control statements in R programming that executes a set of
statements in a loop until the exit condition specified in the loop, evaluates to TRUE.
Syntax
repeat{
Statements
if(exit_condition){
break
}
}
Example:
x <- 1
repeat {
print(x)
x = x+1
if (x == 6){
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
While Loop:
A while loop is one of the control statements in R programming which executes a set of
statements in a loop until the condition (the Boolean expression) evaluates to TRUE.
while(Boolean expression)
{
Statement
}
Example:
16
i<- 1
while (i< 6) {
print(i)
i = i+1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
For Loop:
A for loop is the most popular control flow statement. A for loop is used to iterate a vector.
It is similar to the while loop. There is only one difference between for and while, i.e., in while
loop, the condition is checked before the execution of the body, but in for loop condition is checked
after the execution of the body.
Syntax
for (value in vector) {
statements
}
Example:
x <- c(2,5,3,9,8,11,6)
count<- 0
for (val in x) {
if(val %% 2 == 0) count = count+1
}
print(count)
Output:
[1] 3
Practice Programs:
17
SET A:
SET B:
1. Write a R program to get all prime numbers up to a given number.
2. Accept the cost price and selling price from the keyboard. Find out if the seller has made
a profit or loss and display how much profit or loss has been made.
3. Accept the x and y coordinate of a point and find the quadrant in which the point lies.
4. Write a program to check whether a input number is palindrome or not.
5. Write a program to accept a number and count number of even, odd, zero digits within
that number.
SET C:
1. Use a while loop to simulate one stock price path starting at 100 and random normally
distributed percentage jumps with mean 0 and standard deviation of 0.01 each period. How
long does it take to reach above 150 or below 50?
2. Implement a multiplication game. A while loop that gives the user two random numbers
from 2 to 12 and asks the user to multiply them without using * operator.
Assignment Evaluation
Signature of Instructor
18
Assignment 3: String and Function in R Programming
String:
Any value written within a pair of single quote or double quotes in R is treated as a string.
Internally R stores every string within double quotes, even when you create them with single quote.
Example:
1. grep()
It is used for pattern matching and replacement. grep, grepl, regexpr, gregexpr and regexec
search for matches with argument pattern within each element of a character vector. Here we
subsitute the first and other matches with sub and gsub. sub and gsub perform replacement of the
first and all matches.
Example:
g <- grep("iconHomicideShooting", homicides)
length(g)
2. nchar()
With the help of this function, we can count the characters. This function consists of a
character vector as its argument which then returns a vector comprising of different sizes of the
elements of x. nchar is the fastest way to find out if elements of a character vector are non-empty
strings or not.
Example
# Using nchar() function
nchar("hel'lo")
3. substr():
It is the substrings of a character vector. The extractor replaces substrings in a character
vector.
4. str_length()
The length of strings indicate the number of characters present in the [Link]
function str_length() belonging to the ‘stringr’ package or nchar() inbuilt function of R can
be used to determine the length of strings in R.
Example
# Importing package
19
library(stringr)
5. cat() function
Different types of strings can be concatenated together using the cat()) function in R,
where sep specifies the separator to give between the strings and file name, in case we wish to
write the contents onto a file.
Syntax:
All the characters of the strings specified are converted to upper case.
Example:
All the characters of the strings specified are converted to lower case.
Example:
8. Character replacement
Characters can be translated using the chartr(oldchar, newchar, …) function in R, where
every instance of old character is replaced by the new character in the specified set of strings.
Example:
20
chartr("a", "A", "An honest man gave that")
Output:
Example:
Output:
Example:
Output:
"Lear"
Function in R:
A function should be
Syntax
21
func_name<- function (argument) {
statement
Example:
Pow <- function(x,y){
# function to print x raised to the power y
Result <- x^y
Print(paste(x,”raised to the power”, y,”is”,result))
}
Output:
>pow(8,2)
[1] “8 raised to the power 2 is 64”
Example
pow<- function(x, y = 2) {
# function to print x raised to the power y
result<- x^y
print(paste(x,"raised to the power", y, "is", result))
}
Output:
>pow(3)
[1] "3 raised to the power 2 is 9"
Many a times, we will require our functions to do some processing and return back the
result. This is accomplished with the return() function in R.
Syntax
return(expression)
Example:
check<- function(x) {
if (x > 0) {
result<- "Positive"
}
else if (x < 0) {
22
result<- "Negative"
}
else {
result<- "Zero"
}
return(result)
}
Output:
>check(1)
[1] "Positive"
>check(-10)
[1] "Negative"
1. Recursive Function:
A function that calls itself is called a recursive function and this technique is known as
[Link] special programming technique can be used to solve problems by breaking them
into smaller and simpler sub-problems.
Example:
Output:
>[Link](0)
[1] 1
>[Link](5)
[1] 120
23
In-built Functions:
These functions in R programming are provided by R environment for direct execution,
to make our work easier.
Practice Programs:
1. Write a R program to accept a string from user and display the length of the string.
2. Write a R program to accept a string in lowercase and display it uppercase and vice versa
3. Write a program to check whether a input number is prime number or not using user
defined function.
SET A:
1. Write a program to calculate factorial of a input number using user defined function.
2. Write R program to find the factors of a given number using user defined function
3. Write a R Program to connect two different strings.
SET B:
1. Write a program to calculate xy using user defined function (Use default parameters)
2. Write R program to accept a string and character from user and replace all occurrences of
that character from string with other character.
3. Write a recursive function in R to calculate multiplication of all digits of a given input
number.
24
4. Write a function which accepts one number. Function should return 1 if the number is
Perfect No, otherwise function should return 0.
5. Write a function isPrime, which accepts an integer as parameter and returns 1 if the
number is prime and 0 otherwise.
SET C:
1. Write a R program to print the numbers from 1 to 100 and print "Fizz" for multiples of 3,
print "Buzz" for multiples of 5, and print "FizzBuzz" for multiples of both.
2. Write a program to calculate sum of following series up to n terms using user defined
function
Sum=X+X2/2!+X3/3!+……
Assignment Evaluation
Signature of Instructor
25
Assignment 4: Vector and List in R programming
Introduction:
The Vector is the most basic Data structure in R programming. R Vector can hold a collection of
elements of similar types. A vector supports logical, integer, numeric, character, complex, or raw
data type. The elements which are contained in vector known as components of the vector. We can
check the type of vector with the help of the typeof() function. The length is an important property
of a vector. A vector length is basically the number of elements in the vector, and it is calculated
with the help of the length () function. Vector is classified into two parts, i.e., Atomic vectors and
Lists.
There is only one difference between atomic vectors and lists. In an atomic vector, all the elements
are of the same type, but in the list, the elements are of different data types.
Creating vector in R:
For Example:
4. # Mixed Vector and its Type will be Character : e= c("India", 2, "China", 1, TRUE)
5. # Placing or Nesting One Vector inside the another : f = c("UK", "USA", TRUE, FALSE,
b) where b is another Vector
There are various other ways to create a vector in R, which are as follows:
1. Create R Vector using Range: In R programming, there is a special operator called Range
or Colon, and this will help to create a vector. For example
2. Using the seq() function: In R, we can create a vector with the help of the seq() function. A
sequence function creates a sequence of elements as a vector. For example
1. v1=seq(1,5) #v1 will be 1,2,3,4,5
26
2. v2=seq(1,10,by=2) #v2 will be 1,3,5,7,9
3. v3=seq(1,4,[Link]=6) #v3 will be 1.0,1.6,2.2,2.8,3.4,4.0
Atomic vectors in R:
Atomic vectors are created with the help of c() function. In R, there are four types of atomic
vectors. These atomic vectors are numeric vector, integer vector, character vector and logical
vector.
1. Numeric vector: The decimal values are known as numeric data types in R. If we assign a
decimal value to any variable d, then this d variable will become a numeric type. A vector
which contains numeric elements is known as a numeric vector. For example
>f=c("shubham","arpita","nishka","vaishali")
>g=[Link](c(123, 234))
>d='shubham'
>e="Arpita"
4. Logical vector: The logical data types have only two values i.e., True or False. These values
are based on which condition is satisfied. A vector which contains Boolean values is known
as the logical vector. For example
> a=10
> b=4
> c=8
> log_vec=c(a>b, b<c, c>a, c<a)
> log_vec # it prints TRUE TRUE FALSE TRUE
27
Accessing elements of vectors:
We can access the elements of a vector with the help of vector indexing. Indexing
denotes the position where the value in a vector is stored. Indexing will be performed with the
help of integer, character, or logic.
1. Indexing with integer vector: On integer vector, indexing is performed in the same way as
we have applied in C. There is only one difference, i.e., in C the indexing starts from 0, but in
R, the indexing starts from 1. we perform indexing by specifying an integer value in square
braces [] next to our vector. For example
> d=c(10,20,30,40,50)
>d #Prints 10 20 30 40 50
> d[2] # Prints 20
> d[3] # Prints 30
> d[2:4] #Prints 20 30 40
2. Indexing with a character vector: In character vector indexing, we assign a unique key to
each element of the vector. These keys are uniquely defined as each element and can be
accessed very easily. For example
> Stud=c(“Rollno”=101, “Marks”=80.74)
> Stud[“Rollno”] #prints 101
>Stud[“Marks”] #prints 80.74
>Stud[c(“Rollno”,”Marks”)] #prints 101 80.74
3. Indexing with a logical vector: In logical indexing, it returns the values of those positions
whose corresponding position has a logical vector TRUE. For example
> vec=c(1,2,3,4,5,6)
>vec[c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE)] #It
prints 1 2 5
4. Access using Vector: In this example, we will show how to access the Vector elements using
another Vector in R. for example
>a =c("India", "China", "Japan", "UK", "USA", "Russia", "Sri Lanka")
> b =c(2, 4, 6)
>print(a[b]) # It prints China UK Russia
>print(a[c(5, 7)]) # It prints USA Sri Lanka
>print(a[c(7, 4, 1)]) # It prints Sri Lanka UK India
5. Using Negative Values in R: We can access the Vector elements using Negative values and
the Boolean values. In R Vectors, Negative index position is used to omit those values. For
example
>a=c("India", "China", "Japan", "UK", "USA", "Russia”)
>print(a[-3]) #it prints India China UK USA Russia
>b =c(-3, -6)
>print(a[b]) #it prints India China UK USA
28
>print(a[c(-4, -6)]) #it prints "India" "China" "Japan" "USA"
Vector Operation:
1. Combining Vectors: The c() function is not only used to create a vector, but also it is
also used to combine two vectors. By combining one or more vectors, it forms a new
vector which contains all the elements of each vector.
>a=c(1,2,3)
>b=c("p","q","r")
>c=c(a,b)
>c #prints "1" "2" "3" "p" "q" "r“
>d=(b,a)
>d #prints "p" "q" "r" "1" "2" "3"
2. Arithmetic operations: We can perform all the arithmetic operation on vectors. The
arithmetic operations are performed member-by-member on vectors. We can add,
subtract, multiply, or divide two vectors. For example
> a=c(8,4,10)
> b=c(2,6,5)
> a+b #10 10 15
> a-b #6 -2 5
> a*b #16 24 50
> a/b #4.0000000 0.6666667 2.0000000
> a%%b #0 4 0
> a%/%b #402
29
R List:
Lists are the objects of R which contain elements of different types such as number, vectors,
string and another list inside it. It can also contain a function or a matrix as its elements.
A list is a data structure which has components of mixed data types. We can say, a list is a
generic vector which contains other objects.
In R, the list is created with the help of list() function.
> a_vec=c(1,2,3)
> b_vec=c("Pune","Mumbai")
>list_var=list(2.3,45L,"R Programming", TRUE, a_vec,b_vec)
> print(list_var)
# Here print(list_var) will display the content of list on console as ouput
30
Manipulation of list elements:
R allows us to add, delete or update elements in the list. We can update an element of a list from
anywhere, but elements can add only at the end of the list. To remove an element from a specified
index, we will assign it a NULL value.
We can update the element of a list by overriding it from the new value.
> list1=list (10, 20, 30)
>list1 #display 10 20 30
>list1 [4] =40
>list1 #display 10 20 30 40
>list1[2]=200
>list1 #display 10 200 30 40
>list1[4]=NULL
>list1 #display 10 200 30
Merging List:
R allows us to merge one or more lists into one list. Merging is done with the help of the list ()
function also. To merge the lists, we have to pass all the lists into list function as a parameter,
and it returns a list which contains all the elements which are present in the lists.
>even=list (2, 4, 6)
>odd=list (1, 3, 5)
> mix=list(even, odd)
> print (mix) #display 2 4 6 1 3 5
31
vec=c()
a=1
while(a<=n)
{
num=[Link](readline(prompt="Enter Elemnt="))
vec[a]=num
a=a+1
}
cat("\n Original Vector=")
print(vec)
cat("\n Maximum elemennt of vector=",max(vec))
cat("\n Minimum elemennt of vector=",min(vec))
Q.) Write an R program to sort a list of 10 strings in ascending and descending order.
n=[Link](readline(prompt="How many strings u want to store in list="))
lst=list()
for(a in seq(1,n))
{
lst[a]=readline(prompt="Enter any String=")
}
b=unlist(lst)
b=sort(b)
lst=list(b)
cat("\n List in Ascending Order=")
print(lst)
b=sort(b,decreasing=TRUE)
lst=list(b)
cat("\n List in Descending Order=")
print(lst)
Practice Programs:
1. Write a R program to create a vector of a specified type and length. Create vector of
numeric, complex, logical and character types of length 6.
2. Write a R program to add, multiply and divide two vectors of integers type and length 3.
3. Write a R program to create a list containing strings, numbers, vectors and a logical
values.
32
4. Write a R program to list containing a vector, a matrix and a list and give names to the
elements in the list. Access the first and second element of the list.
SET A:
1. Write an R program to sort a Vector in ascending and descending order.
2. Write an R program to find Sum, Mean and Product of a Vector.
3. Write a R program to sort a Vector in ascending and descending order.
4. Create a list containing a four vectors and give names to the elements in the list
5. Write a R program to merge two given lists into one list.
6. Write a R program to convert a given list to vector.
7. Write a R program to create a list named s containing sequence of 15 capital letters,
starting from ‘E’.
SET B:
1. Write a R program to find all elements of a given list that are not in another given list.
2. Write a R program to extract all elements except the third element of the first vector of a
given list.
3. Write a script in R to create a list of cities and perform the following
a. Give names to the elements in the list.
b. Add an element at the end of the list.
c. Remove the last element.
d. Update the 3rd Element
4. Write a script in R to create a list of students and perform the following
a. Give names to the students in the list.
b. Add a student at the end of the list.
c. Remove the first Student.
d. Update the second last student.
5. Write a script in R to create a vector of numbers and perform the following
a. Search for specific element
b. Count the occurrences of specific element
c. Access the last element of given vector
SET C:
1. Write a R program to extract every nth element of a given vector.
2. Write a R program to select second element of a given nested list.
Assignment Evaluation
Signature of Instructor
33
Assignment 5: Arrays and Matrices in R programming
R Arrays:
In R, arrays are the data objects which allow us to store data in more than two dimensions. In R,
an array is created with the help of the array() function.
Syntax: array_name <- array (data, dim = (row_size, column_size, matrices), dim_names))
Where,
1. data: The data is the first argument in the array() function. It is an input vector which is
given to the array.
2. row_size: This parameter defines the number of row elements which an array can store.
3. column_size: This parameter defines the number of columns elements which an array
can store.
4. Matrices: This parameter defines number of arrays to create.
5. dim_names: This parameter is used to change the default names of rows and columns. It
is list of 3 vectors, where first vector correspond to row names, second vector represent
column names and third vector represent matrix name.
Ex:
>d=array(c(1,2,3,4,5,6,7,8,9),dim=c(3,3,1),dimnames=list(c("r1","r2","r3"),c("c1","c2","c3"),c("
m1")))
>print(d)
, , m1
c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9
34
Accessing Subset of a Array Elements:
In our previous example, we show you how to access the single element from tan Array. In this
example, we will show how to access the subset of multiple items from the Array. To achieve the
same, we use the R array A as follows
R Matrix:
The Matrix in R is the most two-dimensional Data structure. In R Matrix, data is stored in row
and columns, and we can access the matrix element using both the row index and column index.
A matrix is created with the help of the vector input to the matrix function. On R matrices, we
can perform addition, subtraction, multiplication, and division operation. In the R matrix,
elements are arranged in a fixed number of rows and columns. In R, we use matrix function,
which can easily reproduce the memory representation of the matrix. In the R matrix, all the
elements must share a common basic type.
R provides the matrix() function to create a matrix.
Syntax of creating Matrix: matrix(data, nrow, ncol, byrow, dim_name)
Where,
35
1. Data: The first argument in matrix function is data. It is the input vector which is the data
elements of the matrix.
2. Nrow: It is the number of rows in the matrix.
3. Ncol: It is the number of columns in the matrix.
4. Byrow: If its value is true, then the input vector elements are arranged by row.
5. dim_name: The dim_name parameter is the name assigned to the rows and columns.
For Example M1= matrix(c (11, 13, 15, 12, 14, 16), nrow =2, ncol =3, byrow = TRUE)
R = matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_n
ames))
Different ways of creating Matrix in R:
1. # R Create Matrix
>A=matrix(c(1:12), nrow = 3, ncol = 4) >print(A)
2. # Elements are arranged sequentially by column.
>B=matrix(c(1:12), nrow = 3, ncol = 4, byrow = FALSE) >print(B)
3. # Elements are arranged sequentially by row.
>D=matrix(c(1:12), nrow = 3, ncol = 4, byrow = TRUE)
4. # It will create a Matrix of 3 Rows and the remaining elements will be arranged
Accordingly
>A=matrix(c(1:12), nrow = 3)
5. # It will create a Matrix of 4 Columns and the remaining (row) elements will be arranged
Accordingly
>B=matrix(c(1:12), ncol = 4)
6. # It will create a Matrix of 3 rows and 4 Columns
> D=matrix(c(1:12), 3, 4)
7. # It will create a Matrix of 3 rows
>E=matrix(c(1:12), 3)
8. # It will create a Matrix of 4 Rows. To create 4 Columns you have to specify ncol = 4
explicitly
>G=matrix(c(1:12), ncol=4)
36
Define Row names and Column names for matrix in R:
37
>print(A[c(1, 2), c(3, 4)])
3. # Access All the element at 2nd and 3rd row.
>print(A[c(2, 3), ])
4. # Access All the element at 1st and 4th Column.
>print(A[ , c(1, 4)])
5. # Access All the element except 2nd row.
>print(A[-2, ])
6. # Access All the element except 2nd row and 3rd Columm.
>print(A[-2, -3])
7. # Access All the element except 3rd and 4th Columm.
>print(A[, c(-3, -4)])
38
Matrix Arithmetic in R:
R Arithmetic Operators are used on Matrices to perform arithmetic Operations.
# Create 2x3 matrices.
>a=matrix( c(15, 34, 38, 44, 75, 93), nrow = 2)
>b=matrix( c(10, 20, 30, 40, 50, 60), nrow = 2)
1. # Addiing two Matrices
>print(a + b)
2. # Subtraction One Matrix from another
>print(a - b)
3. # R Matrix Multiplication
>print(a * b)
4. # Matrix Division
>print(a / b)
Practice Programs:
1. Write a R program to create an array of two 3x3 matrices each with 3 rows and 3
columns from two given two vectors.
2. Write a R program to create a blank matrix.
3. Write a R program to create a matrix taking a given vector of numbers as input. Display
the matrix.
4. Write a R program to create a two-dimensional 5x3 array of sequence of even integers
greater than 50.
5. Write a R program to convert a given matrix to a 1 dimensional array.
SET A:
1. Write a R program to create a matrix taking a given vector of numbers as input. Display
the matrix.
2. Write a R program to create a matrix taking a given vector of numbers as input and
define the column and row names. Display the matrix.
3. Write a R program to access the element at 3rd column and 2nd row, only the 3rd row
and only the 4th column of a given matrix.
4. Write an R program to create three vectors a,b,c with 3 integers. Combine the three vectors
to become a 3×3 matrix where each column represents a vector. Print the content of the
matrix.
5. Write an R program to create a list of elements using vectors, matrices and a functions.
Print the content of the list.
SET B:
1. Write a R program to create an array of three 3x2 matrices each with 3 rows and 2
columns from two given two vectors of different length.
39
2. Write a R program to create an array of two 3x3 matrices each with 3 rows and 3
columns from two given two vectors. Print the second row of the second matrix of the
array and the element in the 3rd row and 3rd column of the 1st matrix.
3. Write a R program to access the element at 3rd column and 2nd row, only the 3rd row
and only the 4th column of a given matrix.
4. Write a R program to create two 2x3 matrices and add, subtract, multiply and divide the
matrix elements.
5. Write an R program to convert a given matrix to a list and print list in ascending order.
SET C:
1. Write a R program to combine three arrays so that the first row of the first array is
followed by the first row of the second array and then first row of the third array.
2. Write a R program to find row and column index of maximum and minimum value in a
given matrix.
Assignment Evaluation
Signature of Instructor
40
Assignment 6: Factor and Data Frame in R language
R factors:
Factors are the data objects which are used to categorize the data and store it as levels. In order to
categorize the data and store it on multiple levels, we use the data object called R factor. They
are useful in the columns which have a limited number of unique values. Like "Male, "Female"
and True, False etc. They are useful in data analysis for statistical modeling.
By default, R always sorts levels in alphabetical order.
The command used to create or modify a factor in R language is – factor() with a vector as input.
The two steps to creating a factor are:
1. Creating a vector
2. Converting the vector created into a factor using function factor()
# Creating a vector:
>x=c("female", "male", "male", "female")
>print(x) #it prints "female" "male" "male" "female"
Further one can check the levels of a factor by using function levels(). Function [Link]() is used
to check whether the variable is a factor and returns “TRUE” if it is a factor.
>gender=factor(c("female", "male", "male", "female"));
>print([Link](gender))
Function class() is also used to check whether the variable is a factor and if true returns “factor”.
>gender=factor(c("female", "male", "male", "female"));
>class(gender)
41
For selecting all the elements of the factor gender except ith element, gender[-i] should be used.
>gender[-3]
Modification of a Factor
After a factor is formed, its components can be modified but the new values which needs to be
assigned must be in the predefined level. For example
>gender[2]<-“female”
Data Frame in R:
The Data Frame in R is a table or two-dimensional data structure. In R Data Frames, data is stored
in row and columns, and we can access the data frame elements using the row index and column
index. A data frame is a list of variables, and it must contain the same number of rows with unique
row names. The Column Names should not be Empty
The data frame’s data can be only of three types- factor, numeric and character type.
Data frame in R is created as follows
>Id=c(1:5)
>Name=c(“Nilesh”, “Suresh”, “Ramesh”, “Kamlesh”, “Rajesh”)
>Salary=c(80000, 70000, 90000, 50000, 60000)
>employee=[Link](Id, Name,Salary)
> print(employee) will print
Id Name Salary
1 1 Nilesh 80000
2 2 Suresh 70000
3 3 Ramesh 90000
4 4 Kamlesh 50000
5 5 Rajesh 60000
# Names function will display the Index Names of each Item >print(names(employee))
> print(names(employee))
42
[1] "Empid" "Full_Name" "income"
>Id=c(1:5)
>Name=c(“Nilesh”, “Suresh”, “Ramesh”, “Kamlesh”, “Rajesh”)
>Salary=c(80000, 70000, 90000, 50000, 60000)>
>employee=[Link]("Empid" = Id, "Full_Name" = Name, “Income" = Salary)
1. # Accessing all the Elements (Rows) Present in the Name Items (Column)
>employee["Name"]
2. # Accessing all the Elements (Rows) Present in the 3rd Column (i.e., Occupation)
>employee[3]
3. #Accessing Name column as vector
> employee[[“Full_Name"]] or
>employee[[2]]
4. # Accessing Element at 1st Row and 2nd Column
>employee[1, 2]
5. # Accessing Element at 4th Row and 3rd Column
>employee[4, 3]
6. # Accessing All Elements at 5th Row
>employee[5, ]
7. # Accessing All Item of the 4th Column
>employee[, 4]
43
> employee$dept=c(“Comp”, “Math”, “Ele”, “Stat”, “Eng.”)
2. rbind(Data Frame, Values): This method is used to add extra Row with values.
Ex. # Adding Extra Row
>rbind(employee, list(7, “Kamlesh", 8000))
44
2. class(Data Frame): This method will tell you the class of the Data Frame
3. length(Data Frame): This method will count the number of items (columns) in a Data
Frame
4. nrow(Data Frame): This method will return the total number of Rows present in the
Data Frame.
5. ncol(Data Frame): This method will return the total number of Columns available in the
Data Frame.
6. dim(Data Frame): This method will return the total number of Rows and Columns
present in the Data Frame.
7. str(Data Frame): This method returns the structure of the data present in the Data
Frame.
8. summary(Data Frame): This R Programming method returns the nature of the data and
the statistical summary such as Minimum, Median, Mean, Median, etc.
Practice Programs:
1. Write a R program to find the levels of factor of a given vector.
2. Write a R program to create a data frame from four given vectors.
3. Write a R program to count the number of NA values in a data frame column.
SET A:
1. Write a R program to change the first level of a factor with another level of a given
factor.
45
2. Write a R program to create a data frame from four given vectors and display the
structure and statistical summary of a data frame.
3. Write a R program to display second row using row index and third column using
column name of a data frame.
4. Write a R program to create a data frame using two given vectors and display the
duplicated elements and unique rows of the said data frame.
5. Write a R program to call the (built-in) dataset airquality. Remove the variables 'Solar.R'
and 'Wind' and display the data frame.
SET B:
1. Write an R program to concatenate two given factor in a single factor and display in
descending order.
2. Write a R program to extract the five of the levels of factor created from a random
sample from the LETTERS.
3. Write a R program to compare two data frames to find the row(s) in first data frame that
are not present in second data frame.
4. Write a R program to create a data frame from four given vectors and perform the
following
a. add a new column in a given data frame
b. add new row to data frame.
c. drop specific column by name from a given data frame.
d. drop row by number from a given data frame.
5. Write a R program to create a data frame from four given vectors and perform the
following
a. Extract 3rd and 5th rows with 1st and 3rd columns from a given data frame.
b. Sort and display given data frame by specific column.
SET C:
1. Write a R program to create inner, outer, left, right join(merge) from given two data
frames.
2. Write a R program to save the information of a data frame in a file and display the
information of the file.
Assignment Evaluation
Signature of Instructor
46
Assignment 7: Data Analysis
R CSV Files:
A Comma-Separated Values (CSV) file is a plain text file which contains a list of data. These files
are often used for the exchange of data between different applications. These files can sometimes
be called character-separated values or comma-delimited files. They often use the comma character
to separate data. The idea is that we can export the complex data from one application to a CSV
file, and then importing the data in that CSV file to another application. R allows us to read data
from files which are stored outside the R environment. The file should be present in the current
working directory so that R can read it. We can also set our directory and read file from there.
Getting and setting the working directory:
In R, getwd() and setwd() are the two useful functions.
➢ The getwd() function is used to check on which directory the R workspace is pointing.
➢ And the setwd() function is used to set a new working directory to read and write files from
that directory.
1. # Getting and printing current working directory.
>print(getwd())
2. # Setting the current working directory.
>setwd("C:/Users/ajeet")
47
4. quote: If your character values (FirstName, Education column tc) are enclosed in quotes
then you have to specify the quote type. For double quotes we use: quote = “\”” in r
[Link] function
5. nrows: It is an integer value. You can use this argument to restrict the number of rows to
read. For example, if you want top 5 records, use nrows = 5
6. skip: Please specify the number of rows you want to skip from file before beginning the
csv read. For example, if you want to skip top 2 records, use skip = 2
48
7. #Getting the details of all the students whose name is Nilesh
>details=subset(csv_data,name==“Nilesh")
>print(details)
8. #Getting the details of all the student whose name is Nilesh and rollno is 5
>details=subset(csv_data,rollno==5 & name==“Nilesh”)
9. #Getting the details of all the students who score more than 60 marks
> details=subset(csv_data,marks>60)
>print(details)
10. #using inbuilt dataset mtcars find the number of cars of each gear type
>data=mtcars
>f=factor(data$gear)
>print(table(f))
11. #using inbuilt dataset mtcars find the number of cars having 3 gear and 2 carburetor
>data=mtcars
>d=subset(data,gear==3 & carb==2)
>print(nrow(d))
1. select: Select columns with select(). It returns a subset of the columns of a data frame.
Ex. df=iris
x<-select(df,c(Species,[Link]))
head(x)
49
2. filter: Filter rows with filter().It extracts a subset of rows from a data frame based on
logical conditions.
3. arrange: Arrange rows with arrange(). It helps to reorder rows of a data frame
Ex x<-arrange(mtcars, cyl)
Print(x)
y<-arrange(mtcars, desc(cyl))
print(y)
4. group_by:
The group_by() function first sets up how you want to group your data.
The general operation here is a combination of splitting a data frame into separate pieces
defined by a variable or group of variables (group_by()), and then applying a summary
function across those subsets (summarize()).
Ex cyl <- group_by(mtcars, cyl)
summarise(cyl, mean(disp), mean(hp))
Practice Programs:
1. Using inbuilt dataset women perform the following
a. display all rows of dataset having height greater than 120
b. display all rows of dataset in ascending order of weight
2. Using the inbuilt mtcar dataset perform the following
a. Display all the cars having 4 gears
b. Display all the cars having 3 gears and 2 carburetor.
3. Using inbuilt PlantGrowth dataset perform the following
a. Find the flowers of each type of group
b. Display all rows of type “ctrl” having weight greater than 5.0
SET A:
1. Using the inbuilt mtcar dataset perform the following
a. Display all the cars having mpg more than 20
b. Subset the dataset by mpg column for values greater than 15.0.
2. Using the inbuilt airquality dataset perform the following
a. Find the temperature of day 30 of month 8
b. Display the details of all the days if the temperature is greater than 90
3. Using the inbuilt airquality dataset perform the following
a. Subset the dataset for the month July having Wind value greater than 10
b. Find the number of days having temperature less than 60
SET B:
1. Using iris inbuilt dataset perform the following
a. Find the flowers of each type of species
50
b. Find the Sepal length and width of the flower of type setosa having maximum
petal length
2. Using iris inbuilt dataset perform the following
a. Display details of all flowers of type virginica in ascending order of petal length.
(use order function)
b. Display details of first five flowers of type setosa having maximum petal length.
3. Using inbuilt PlantGrowth dataset perform the following
a. Display details of all plant having weigth greater than 5.80
b. Display details of all Plants of group trt1 in ascending order of their weight.
SET C:
1. Using inbuilt ToothGrowth dataset perform the following
a. Find supplement (supp) wise maximum and minimum length of tooth
b. Display details of first 3 tooth having minimum length for supplement OJ for dose
1.0
Assignment Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
Signature of Instructor
51
Assignment 8: Data Visualization
Introduction:
Data visualization is an efficient technique for gaining insight about data through a visual medium.
With the help of visualization techniques, a human can easily obtain information about hidden
patterns in data that might be neglected.
By using the data visualization technique, we can work with large datasets to efficiently obtain
key insights about it.
In R, we can create visually appealing data visualizations by writing few lines of code.
Advantages of Data Visualization in R:
1. Understanding: It is easier to understand through graphics and charts than a written
document with text and numbers. Thus, it can attract a wider range of audiences. Also, it
promotes the widespread use of business insights that come to make better decisions.
2. Efficiency: Its applications allow us to display a lot of information in a small space.
Although, the decision-making process in business is inherently complex and
multifunctional, displaying evaluation findings in a graph can allow companies to organize
a lot of interrelated information in useful ways.
R Bar Charts:
A bar chart is a pictorial representation in which numerical values of variables are represented by
length or height of lines or rectangles of equal width. A bar chart is used for summarizing a set of
categorical data. In bar chart, the data is shown through rectangular bars having the length of the
bar proportional to the value of the [Link] R, we can create a bar chart to visualize the data in
an efficient manner.
For this purpose, R provides the barplot() function, which has the following syntax:
Syntax: barplot(h, xlab, ylab, main, [Link], col) where
1. h: A vector or matrix which contains numeric values used in the bar chart.
2. xlab: A label for the x-axis.
3. ylab: A label for the y-axis.
4. main: A title of the bar chart.
5. [Link]: A vector of names that appear under each bar.
6. Col: It is used to give colors to the bars in the graph.
Example: # Creating the data for Bar chart
> h=c(100,300,500,200,350,50)
> barplot(h, xlab="Year", ylab="Strength", main="Bar Chart", [Link] = c (2000,
2001, 2002,2003,2004,2005))
52
Creating a barplot in R by reading data from CSV file:
[Link] File
53
>barplot(d$[Link], xlab="Month", ylab="Sale Amount", main="Sale Report",
[Link]=d$Month, col="red", border="blue", horiz = TRUE, density=100)
[Link] File
>fy=d$FY
>sy=d$SY
>ty=d$TY
>data=matrix(c(fy,sy,ty),ncol=3,byrow=TRUE)
>barplot(data, xlab="class", ylab="Strength", main="Course Wise Student Strength",
[Link]=d$Class, col= c ("red", "blue", "green"))
R Scatterplots:
In a scatterplot, the data is represented as a collection of points. Each point on the scatterplot
defines the values of the two variables. One variable is selected for the vertical axis and other for
the horizontal axis.
54
The scatter plots are used to compare variables. A comparison between variables is required
when we need to define how much one variable is affected by another variable.
Scatterplot is created using plot() function. The syntax is as follows
Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes) where,
1. X- It is the dataset whose values are the horizontal coordinates.
2. Y- It is the dataset whose values are the vertical coordinates.
3. Main- It is the title of the graph.
4. Xlab- It is the label on the horizontal axis.
5. Ylab- It is the label on the vertical axis.
6. Xlim- It is the limits of the x values which is used for plotting.
7. Ylim- It is the limits of the values of y, which is used for plotting.
8. axes- It indicates whether both axes should be drawn on the plot.
Example:
Following scatterplot show the relationship between HP and MPG attribute of mtcars dataset
>plot(mtcars$hp, mtcars$mpg, xlab="HP", ylab="Milage", xlim=c(50,350), ylim=c(9,36), main=
"HP Vs Milage", col="red")
R Histogram:
A histogram is a type of bar chart which shows the frequency of the number of values which are
compared with a set of values ranges. The histogram is used for the distribution, whereas a bar
chart is used for comparing different entities.
In the histogram, each bar represents the height of the number of values present in the given
range.
For creating a histogram, R provides hist() function, which takes a vector as an input and uses
more parameters to add more functionality.
There is the following syntax of hist() function:
Syntax: hist(v, main, xlab, ylab, xlim, ylim, breaks, col, border) where
1. V: It is a vector that contains numeric values.
2. Main: It indicates the title of the chart.
3. Col: It is used to set the color of the bars.
4. Border: It is used to set the border color of each bar.
5. Xlab: It is used to describe the x-axis.
6. Ylab: It is used to describe the y-axis.
7. Xlim: It is used to specify the range of values on the x-axis.
8. Ylim: It is used to specify the range of values on the y-axis.
9. Breaks: It is used to mention the width of each bar.
55
Example: Consider Vector V which consists of weight of different students
> V=c(55,67,78,82,57,62,74,80,52,64,76,66)
>hist(v, xlab = "Weight", ylab="Frequency", col = "green", border = "red")
R Boxplot:
Boxplots are a measure of how well data is distributed across a data set. This divides the data set
into three quartiles. This graph represents the minimum, maximum, average, first quartile, and
the third quartile in the data set. Boxplot is also useful in comparing the distribution of data in a
data set by drawing a boxplot for each of them.
R provides a boxplot() function to create a boxplot. There is the following syntax of boxplot()
function
Syntax: boxplot(data or formula, xlab, ylab, main, names, col) where,
1. data: DataFrame, or List that contains the data to draw boxplot.
2. Xlab: It is used to describe the x-axis.
3. Ylab: It is used to describe the y-axis.
4. Main: It is used to give a title to the graph.
5. Names: It is the group of labels that will be printed under each boxplot.
Creating a Boxplot in R Programming:
In this example, we create a Boxplot using the airquality data set
>a=airquality
> boxplot(a$Wind)
56
Use Formula to create a Boxplot in R:
In this example, we create a Boxplot using the formula argument
formula: It should be something like value~group, where value is the vector of numeric values,
and the group is the column you want to use as a group by.
e.g., if you want to draw a boxplot for Monthwise wind speed, then value = Wind and group =
Month
>a=airquality
>boxplot(a$Wind~a$Month, xlab="Month", ylab="Wind Speed", main="Box Plot",
col="red")
Practice Programs:
1. Write an R program to draw an empty plot and an empty plot specifies the axes limits of
the graphic.
2. Using inbuilt airquality dataset make a scatter plot to compare Wind speed and
temperature.
3. Using inbuilt iris dataset create Histogram for [Link] values
4. Using iris dataset draw horizontal bar plot for Petal length values for species setosa
SET A:
SET B:
57
b. Draw a scatter plot showing the relationship between wt and mpg for all the cars
having 4 gears
2. Using airquality dataset
a. Show the statistical summary using box plot for Temprature value of month June
b. Using histogram show the frequency of number of days for Temp values of month
August
SET C:
1. Using inbuilt mtcars dataset show a stacked bar graph of the number of each gear type
and how they are further divided out by cyl
2. Draw boxplot to show the distribution of mpg values per number of gears
Assignment Evaluation
Signature of Instructor
58
59