Z - Notes - Introduction To R Complete
Z - Notes - Introduction To R Complete
It is an open-source programming language. Before R, there was a language called S. It was basically
designed for the data analyst and for statistical use. It has a limitation that it did not come from a
traditional programming background. R was created and made public by Ross Ihaka and Robert
Gentleman in the Department of Statistics at the University of Auckland in 1996. Finally ,in 2000 R
version, 1.0.0 was created by the R committee and people associated with S. it was designed as
statistical software and data analysis tool.
Many people around the world make contributions in the form of new features, bug fixes, or both.
This new versions are made available to the public with new releases.
R has many statistical packages. It has maintained S philosophy and also has strong programming for
developing new tools.
What is r studio?
It is Integrated Development Environment (IDE) for R. It is a GUI where you can write the code, see
the result, see the variables, see the plots, etc…
1. Desktop Version
2. Server Version.
How to install R?
_______________________________________________________________________________________________________
1
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Step3: .exe file will get downloaded. Run the file, keep the default selection. Install it.
_______________________________________________________________________________________________________
2
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Step 3: .exe file will get downloaded. Run the file. Keep the default selection.
_______________________________________________________________________________________________________
3
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
The codes will be executed on R studio which has following window panels:
1. Console: You can type the command here and also you can see the printed result.
2. Environment: variables which are generated during the course of programming are stored here.
3. History: All commands which you have used from the beginning can be found here.
4. Files: All files/directories that are available in workspace of R can be seen here.
5. Plots: The plots (graphs/figures) which are generated can be seen here.
6. Packages: It gives the information about the packages installed in R studio. Also you can install
new packages as per the requirement.
7. Help: The R document from which you can get help for inbuilt functions.
8. Viewer: To see the local web content generated by R application.
_______________________________________________________________________________________________________
4
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
The single line command can be executed on the console window. To write a complete code
perform the following steps:
Step 1:
Go to File option→ New file→R script
Step 2:
A window panel will get open with an “untitled” name. Write the code in the opened panel. Go to
File →Save as. Save the code in any of your folders with some relevant names.
_______________________________________________________________________________________________________
5
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Step 3:
To run the code there are following options:
1. Run (CTRL+Enter):
Click the Run option present on the top right. This will run only the single statement where you
have kept your cursor and the corresponding result can be seen in the console window. For
example to run four consecutive statements with the run option you have to click ok the Run
option four times.
_______________________________________________________________________________________________________
6
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
You can also run selected statements together by selecting the required statements and then press
Run button.
_______________________________________________________________________________________________________
7
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Comments are used to improve the readability of the code. You can write a comment for the
statement you have used to explain the purpose of that statement. Indirectly the comments explain
the algorithm. Hence a new user can underverynd vey easily why that statement is used.
1. Single line Comment: Use symbol “#” in front of the statement which you want to use as
comment. Here line No.1 and line No 4 are the comments.
_______________________________________________________________________________________________________
8
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
2. Multiple lines:
Select the multiple lines with cursor and press ctrl+shift+c all selected lines will be converted
to comments.
Or
Select multiple lines using the cursor, click on the option Code on the left top then select
comment/Uncomment lines.
_______________________________________________________________________________________________________
9
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
How to clean/clear the console and the variables?
To clear the console you can use the command Ctrl+L. To clear the variables you can use the
symbol of brush present on the top of Global environment on the top right-hand side.
The functionality which we get after installing R is very basic. The additional functionality can be
downloaded as and when required in the form of packages. These packages are created and
updated by different developers and can be obtained from different repositories like CRAN, GITHUB
etc.
>[Link]("dslabs")
OR
In RStudio, you can navigate to the Tools tab and select install packages.
_______________________________________________________________________________________________________
10
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
_______________________________________________________________________________________________________
11
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
We can install more than one package at once by feeding a character vector to this function:
[Link](c("tidyverse", "dslabs"))
>[Link]("[Link]") ## any general name but should have extension .RData. When you
want to retrieve it back you can select open file option present in File tab on left top above the
script pane.
Help Command- R contains many inbuilt function. You can get help about these functions by typing
>help (function_name)
for example:
>help (sort)
OR
> ?sort
It gives the information about the function (here about the function sort).
>[Link] ()
R as a calculator:
❖ You can store the values in the objects and can read the values as well. For example let us
store 1 in object named "a" and 5 in object named "b"
_______________________________________________________________________________________________________
13
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
# store 1 in a
>a=1
# You can also use assignment operator as “=” or "<-" i.e a<-1
#Initialize b with 3
>b<-3
#Multiply a and b and store the result in c
>c<-a*b
# R will not print anything by its own. If you want to the values stored in a and b either you
have to type a and b in console
>a ## displays value of a
>b ## displays value of b
OR
you can use print command.
print(a)
❖ You can also store more than one value in variable a by concate command. This is called as
vector.
>a<- c(1,3,4)
>a
[1] 1 3 4
❖ You can store data in different variable and then concate then
a<-c(1,2,3)
b<-c(4,5,6)
c<-c(a,b)
>c
[1] 1
❖ You can use “:” colon operator to store more than one value which is discussed in detail late
on.
>b<-100:130
[1] 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
[20] 119 120 121 122 123 124 125 126 127 128 129 130
_______________________________________________________________________________________________________
14
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
You’ll notice that a [1] appears next to your result. R is just letting you know that this line
begins with the first value in your result. Some commands return more than one value, and
their results may fill up multiple lines. For example, the command 100:130returns 31 values;
it creates a sequence of integers from 100 to [Link] that new bracketed[ ] numbers
appear at the start of the second of output. These numbers just mean that the second line
begins with the 20th value in the result.
The colon operator (+) returns every integer between two integers. It is an easy way to
create a sequence of numbers. If you type an incomplete command and press Enter, R will
display a + prompt, which means it is waiting for you to type the rest of your command.
Either finish the command or hit Escape to start over:
For Example:
>5 - ## You have pressed enter after ‘-‘ sign. R is waiting for next command.
+
+1
[1] 4
Exercises:
[Link]
Variables are used to store some information. Variables are used to store some values which
you will require for your program. Creating variables means reserving some memory to store
the values. A variable itself is not declared of any data type, rather it gets the data type of the R
- object assigned to it. You can change a variable’s data type of the same variable again and
again when using it in a program.
_______________________________________________________________________________________________________
15
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
2. Data Types:
Following are the data types in R:
1. Logical
2. Integer
3. Numeric
4. Complex
5. Character
Each of the above data types has some set of values assigned to it. The class (type) can be
checked as follows:
[Link](variable_name)
It gives you one of the above mentioned type.
OR
[Link].data_type(variable_name)
It gives you either true or false depending on the result.
_______________________________________________________________________________________________________
16
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
2. Numeric Type: These are double precision real numbers. The numbers which you enter are
by default saved as numeric data type. This means that even if you see a number like “1” or “2”
in R, which you might think of as integers, they are likely represented behind the scenes as
numeric objects (so something like “1.00” or “2.00”). If you explicitly want an integer, you need
to specify the L suffix. So entering 1 in R gives you a numeric object; entering 1L explicitly gives
you an integer object.
>[Link](2)
[1] TRUE
Forexample, the operation 2/3 performs real division, which results in 0.666667
>x <- 2/3
> print(class(x))
[1] "numeric"
It is the default computational data type.
3. Integer Type: 2 is not an integer in R. It is a numeric type which is the larger type that
contains all floating-point numbers as well as integers. To get an integer you have to make the
value explicitly an integer, and you can do that using the function [Link] or writing L after
the literal.
>[Link](2)
## [1] FALSE
_______________________________________________________________________________________________________
17
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
>[Link](2L)
## [1] TRUE
>x <- [Link](2)
>[Link](x)
## [1] TRUE
>class(x)
## [1] "integer"
4 Complex Type:
You can use complex numbers as well in R. You can write the complex number as 2+5i.
If you want to convert the complex number to numeric or integer then the imaginary part is
discarded in coercion.
e.g:
>d=2+4i
> class(d)
[1] "complex"
> [Link](d)
[1] 2
Warning message:
imaginary parts discarded in coercion
> [Link](d)
[1] "2+4i" ## converted to character.
5. Character Type: In other languages like “C” you have considered character type for single
character and for multi-character you have used String. But in R they both are treated as
character type only.
e.g
> d="121"
> f=[Link](d)
[1] TRUE
> [Link](d)
[1] 121
> [Link](c)
[1] NA
Warning message:
NAs introduced by coercion
_______________________________________________________________________________________________________
18
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Note: All conversions/coercion from one data type to another is not possible.
The two characters if concate by concate command gives the following output.
>x<-"joe"
> y<-"ram"
> c(x,y)
[1] "joe" "ram"
> paste(x,y)
[1] "joe ram"
Exercise:
1. Assume s=2 and p=2L. Find the class of s and p . Then convert value of s to integer and save
it in q. Check the class of q now.
2. If you have taken b=4/3 what will be the output when you run following commands:
[Link](b) ---1
ii. class(b)---- numeric
[Link](b)---1.333
[Link] [Link] and [Link] command for b and state what is the output of both the
commands.----FALSE and TRUE
Solution:
>s=2
>p=2L
>class(s)
[1] "numeric"
> class(p)
[1] "integer"
> q<-[Link](s)
> class(q)
[1] "integer"
3. Assign 1 to variable x and 2 to variable y. Then define z=x>y. Print the value of z.----False.
What is the class of z? –Logical
4. Store the string “ My SGPA “ in variable x, “for last semester is” in variable y and 9.12 in
variable z. Now, Print the statement “ My SGPA for last semester is 9.12”.
_______________________________________________________________________________________________________
19
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Data Objects:
Following are the data objects in R:
1. Vectors
2. Lists
3. Matrices
4. Arrays
5. Factors
6. Data Frames.
[Link]:
Vectors are the most basic data object in R. You can create vectors as single element or multi
element vector. All the elements of a vector are of same type.
Creating vectors:
When you store more than one value i.e its length becomes greater than 1 it becomes multiple
element vector. You can use following methods to store more than one value in a vector:
1. Using colon operator:
e.g:
>4:12 ## by default increments by 1.
[1] 4 5 6 7 8 9 10 11 12
>2.2:8.2
[1] 2.2 3.2 4.2 5.2 6.2 7.2 8.2
>2.2:9.1
>x=c(1.1,2.3,4.2)
> x
[1] 1.1 2.3 4.2
_______________________________________________________________________________________________________
20
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
> length(x)
[1] 3
>p=c(1,2,”d”,4,6,”g”)
>p
[1] “1” “2” “d” “4” “6” “g”
>class(p)
>”character
>t=rep(2,5)
[1] 2 2 2 2 2
>f=rep(t,2)
[1] 2 2 2 2 2 2 2 2 2 2
>x=c("mon"=10,"tue"=20,"wed"=30)
> x
mon tue wed
_______________________________________________________________________________________________________
21
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
10 20 30
> b=names(x)
> b
[1] "mon" "tue" "wed"
> k=x["wed"]
> k
wed
30
>d<-p[c(-1,-5,-10)]
>d
[1] "feb" "mar" "apr" "june" "july" "aug" "sept" "nov" "dec"
## Here 1st,5th and 10th element is discarded.
> q<-c(1:12)
> t<-q[c(5:9)]
>t
[1] 5 6 7 8 9
> t[t>6]
[1] 7 8 9
## The values for which the conditions are true are returned.
Modifying a Vector
You can modify a vector using assignment operator.
For example: let vector x contains -3 to 4 values
>x
[1] -3 -2 -1 0 1 2 3 4
_______________________________________________________________________________________________________
22
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
> x[4]<-100
>x
[1] -3 -2 -1 100 1 2 3 4
## The element present at 4th position is modified to 100.
> x[x<0]<-0
>x
[1] 0 0 0 100 1 2 3 4
## Elements are made to zero with logical condition. All elements less than zero
were made equal to 0.
>q<-1:12
[1] 1 2 3 4 5 6 7 8 9 10 11 12
>g=sort(q, decreasing=TRUE)
[1] 12 11 10 9 8 7 6 5 4 3 2 1
>v1
[1] 1 2 3 4 5 6
> sqrt(v1) ## square root
[1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490
> v1^2 ## square of the element
[1] 1 4 9 16 25 36
Exercises:
_______________________________________________________________________________________________________
24
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
4. Create a vector x with elements 1, 5, 2, 3, 7, 6, 8 and create vectors y, z, w
from x using
y = x2, z = 1/x, w = log10x --- y<-x^2 , z=1/x, w<-log(x,10)
5. Suppose age is a vector containing ages of 10 persons as 22, 27, 31, 41, 30,
25, 19, 20, 23, 35
i. Access age of fourth person---age[4]
ii. Create a vector age30 with age of person > 30 --age30<-age[age>30]
iii. Access age of last 3 person -- tail(age,3)
iv. Find number of elements in vector age---length(age)
v. Access ages of persons except 5th and 7th –age[c(-1,-5)]
vi. Create a vector age2 with age of persons between 20 and 25--- age2<-
age[age>20 & age<25]
For example
## Here the variable t is a list which contains two different vectors, one vector
having value 1 2 3 4 and other 5 6 7 8. Note that it has not returned the value
like concatenation command gives for vectors i.e 1 2 3 4 5 6 7 8. Thus there are
two elements in this list which are two vectors.
>t=list(1:4,5:8)
> t
[[1]]
[1] 1 2 3 4
[[2]]
[1] 5 6 7 8
## Following list f consists of three vectors of types character, logical and nume
ric data type.
Ex1:
> v1=c("mon","tue","wed")
> v2=c(T,F)
_______________________________________________________________________________________________________
25
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
> v3=56:80
> f=list(v1,v2,v3)
>f
[[1]]
[1] "mon" "tue" "wed"
[[2]]
[1] TRUE FALSE
[[3]]
[1] 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
>class(f)
[1] “lists”
Ex2:
> s<-list(1:3,T,F)
> s
[[1]]
[1] 1 2 3
[[2]]
[1] TRUE
[[3]]
[1] FALSE
> length(s)
[1] 3
> m<-list(f,s)
> m
[[1]] ## indicates first element of list m
[[1]][[1]] ## indicates first element of first list
( f[1] – mon,tue,wed )
[1] "mon" "tue" "wed"
[[1]][[2]] ## indicates second element of first list
[1] TRUE FALSE
_______________________________________________________________________________________________________
26
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
[[1]][[3]]
[1] 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80
_______________________________________________________________________________________________________
27
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
> s[[1]][[1]] ## accessing the first element of first element of list s
[1] 1
> s[[1]][[3]] ## accessing the third element of first element of list s.
[1] 3
_______________________________________________________________________________________________________
28
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
$b
[1] "red" "blue"
$d
[1] TRUE FALSE TRUE
Exercise:
1. Create a list named ls. The list ls contains following 6 vectors with their
values as follows :
Rollno- 1:4
First name- Ravi,Om,Ajay,Shiv
Last name-Dev,Gandhi,Pande,Rao
Subject-AE,DS,ML,OS
Marks-35,40,38,02
Result –P,P,P,F.
Task To be performed:
1. Print the list ls.
2. Print all the independent element of list ls.
3. Find the class of element of the list.
4. What will be the output of the following commands:
What will be the output for
a)Print(ls[[2]][1])
b) print(ls[[4]][4])
c)print(ls[5])
5. It was found that the marks of Ajay were entered wrongly. The correct marks
should be 45. Replace the marks of Ajay without disturbing the other elements or
without loading the complete list again.
6. Change the subject name of OS to OE. Modify the required element only.
7. It was decided that the data base should also have native place information.
Ravi stays at Pune, Ajay at Mumbai, Shiv at Nashik and Om at Nagpur. Please add
this information also in the list.
8. Add one more student information names Julie Gommes. The marks obtained
by Julie in subject DS is 30 and the result is P. Her native place is Hyderabad.
_______________________________________________________________________________________________________
29
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Homework for Practice:
1. Create the list x which contain numeric vector n(2,3,5), a character vector
s(“aa”,”bb”,”cc”,”dd) , and logical vector b(T,F,T,F), and numeric value 3.
Perform the following task:
[Link] the list print s vector values by list slicing.
[Link] the list find s vector values, and numeric value 3, with the help of
index vector by list slicing
3. From the list find s vector values by member access
4. Modify s vector value replacing “aa” by “tt” and again find s
MATRICES:
Matrices are the R objects where the elements are arranged in two dimensional
formats. It contains rows and columns. The elements are of same type. Matrices
are vectors with “dimension” attribute. The dimension attribute itself is a vector
of length 2 (number of rows and number of columns).
## It enters the data column wise i.e column is filled first and then row by
default.
>m<-matrix(1:6,2,3)
>m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
OR
>m<-matrix(1:6,nrow=2,ncol=3,byrow=FALSE) ## Enters column wise.
>m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> m<-matrix(1:6,nrow=2,ncol=3,byrow=TRUE) ## Enters row wise. Rows are
filled first.
>m
[,1] [,2] [,3]
_______________________________________________________________________________________________________
30
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
[1,] 1 2 3
[2,] 4 5 6
>d<-c(2,5,6)
> e<-c(9,5,5)
> m<-matrix(c(d,e),2,3)
>m
[,1] [,2] [,3]
[1,] 2 6 5
[2,] 5 9 5
2. Dimension Attribute:
Matrix can be created by adding dimension attribute as follows:
>d<-1:8
> dim(d)<-c(2,4) ## Considers rows as 2 and columns as 4.
> print(d)
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
> dim(d) ## It retrieves the assigned values of dimension.
[1] 2 4
_______________________________________________________________________________________________________
31
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
[Link] : The elements are placed row wise.
>m<-rbind(v,w)
> print(m)
[,1] [,2] [,3] [,4] [,5]
v 3 5 6 6 7
w 4 7 8 9 0
ARRAYS:
Arrays are the R data objects which can store data in more than two
dimensions.
Creating Arrays:
_______________________________________________________________________________________________________
33
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
If we create an array of dimension (3, 3, 2) then it creates 2 rectangular
matrices each with 3 rows and 3 columns. An array is created using
the array() function. It takes vectors as input and uses the values in
the dim parameter to create an array.
> v1<-c(1,3,5)
> v2<-c(2,4)
> v3<-c(9,10,11,19)
> a1<-array(c(v1,v2,v3),dim=c(3,3,2))
> a1
, , 1
[,1] [,2] [,3]
[1,] 1 2 10
[2,] 3 4 11
[3,] 5 9 19
, , 2
[,1] [,2] [,3]
[1,] 1 2 10
[2,] 3 4 11
[3,] 5 9 19
Accessing Array:
Like matrix you can access either single element or complete row or complete
column of any of the matrices.
For example:
>d<-a1[2,3,1] ## It gives 2nd row and third column element of 1st matrix
[1] 11
> f<-a1[2,2,] ## It gives 2nd row 2nd column element of both the matrices.
> h<-a1[2,,] ## It gives 2nd row all columns and all matrix data.
Array Operations:
Different arithmetic operations can be done on elements of arrays in the simil
ar fashion as of matrices.
_______________________________________________________________________________________________________
34
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Exercise:
A= and B=
Use a) function matrix b) function cbind c)function rbind. Perform the foll
owing task:
i. What is the largest number present in the matrix A and smallest num
ber in matrix B.---max(A) min(B)
ii. Extract the 2nd row and 3rd column element of matrix A and save it in
variable c.—
c<-A[2,3]
iii. Extract row number 4 of matrix B and save it in vector D. D<-B[4,]
iv. Which is the largest number present in the last column of matrix B?
—max(B[,4])
v. Display the transpose of matrix A and inverse of matrix B. –t(A) solve
(B)
Data Frame:
It is a tabular form structure. Each column of the table should have same number of elements
and each column represents values of one variable. The elements of different columns can be of
different objects (unlike matrices).
_______________________________________________________________________________________________________
35
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Ponting 168 287 257 51.85
Kallis 166 280 224 55.37
Dravid 164 286 270 52.31
Cook 161 291 294 45.35
The data frame for batsmen with most runs can be created as follows:
> match_stat<-[Link](name=c("Tendulkar","Ponting","kallis","
Dravid","cook"),matches=c(200,168,166,164,161),innings=c(329,287,
280,286,291),highestscore=c(248,257,224,270,294),avg=c(53.78,51.8
5,55.37,52.31,45.35))
> match_stat
name matches innings highestscore avg
1 Tendulkar 200 329 248 53.78
2 Ponting 168 287 257 51.85
3 kallis 166 280 224 55.37
4 Dravid 164 286 270 52.31
5 cook 161 291 294 45.35
Getting structure of data frame:
The structure of data frame created can be obtained by function str() as follows:
>str(match_stat)
'[Link]':5 obs. of 5 variables:
$ name : Factor w/ 5 levels "cook","Dravid",..: 5 4 3 2 1
$ matches : num 200 168 166 164 161
$ innings : num 329 287 280 286 291
$ highestscore: num 248 257 224 270 294
$ avg : num 53.8 51.9 55.4 52.3 45.4
[Link] get name of the batsman and his corresponding number of innings and average runs.
> i<-[Link](match_stat$name,match_stat$innings,match_stat$av
g)
> i
match_stat.name match_stat.innings match_stat.avg
1 Tendulkar 329 53.78
2 Ponting 287 51.85
3 kallis 280 55.37
4 Dravid 286 52.31
5 cook 291 45.35
ii. To find Tendulkar highest score and kallis average. i.e accessing 1st and 3rd row and 4th and
5th column.
>res1<-match_stat[c(1,3),c(4,5)]
> res1
highestscore avg
1 248 53.78
3 224 55.37
Data frame has too many rows and columns. You can display few starting or ending entries by
function head and tail as follows:
>head(match_stat,n=2)
name matches innings highestscore avg
1 Tendulakar 200 329 248 53.78
2 Ponting 168 287 257 51.85
>tail(match_stat,n=3)
name matches innings highestscore avg
3 kallis 166 280 224 55.37
4 Dravid 164 286 270 52.31
5 cook 161 291 294 45.35
Operators :
1. Arithmetic
Operator Description
+ Adds two vectors
- Subtracts two vecto
rs
* Multiplies two vecto
Arithmetic rs
/ Divides first number
by second
%% Gives remainder
%/% Gives quotient
^ Gives raised to the p
ower.
For example:
>a<-c(2.4,3,5)
_______________________________________________________________________________________________________
39
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
> b<-c(1.2,3,4.5)
> a+b
[1] 3.6 6.0 9.5
> a-b
[1] 1.2 0.0 0.5
> a/b
[1] 2.000000 1.000000 1.111111
> a*b
[1] 2.88 9.00 22.50
> a%%b
[1] 0.0 0.0 0.5
> a%/%b
[1] 2 1 1
> a^b
[1] 2.859259 27.000000 1397.542486
[Link] Operator
Operato Description
r
< Checks if element of first vector is
less than corresponding element of s
econd vector.
> Checks if element of first vector is
Relational greater than corresponding element
of second vector.
== Checks if element of first vector is
equal to corresponding element of s
econd vector.
<= Checks if element of first vector is
less than or equal to corresponding
element of second vector.
>= Checks if element of first vector is
greater than or equal to correspondi
ng element of second vector.
_______________________________________________________________________________________________________
40
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
!= Checks if element of first vector is
not equal corresponding element of
second vector.
It gives result in terms of Boolean value TRUE or F
ALSE
[Link] operator:
Operato Description
r
& Element wise logical AND operator
. It ANDs each element of first vecto
r by corresponding element of secon
d vector and gives result as TRUE if b
Logical oth are TRUE
| Element wise logical OR operator. I
t ORs each element of first vector by
corresponding element of second ve
ctor and gives result as TRUE if eithe
r of the element is TRUE
! It is called Logical NOT operator. Ta
kes each element of the vector and
gives the opposite logical value.
&& Called Logical AND operator. Takes
first element of both the vectors and
gives the TRUE only if both are TRUE
.
|| Called Logical OR operator. Takes fi
rst element of both the vectors and
gives the TRUE if one of them is TRU
E.
[Link] operator:
Left Assignment:
_______________________________________________________________________________________________________
41
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
<- , = , <<- a<-c(1,2,3)
Right Assignment:
->, ->> c(1,2,3)->a
5. Miscellaneous operator:
1. ‘:’ e.g 1:4 [1] 1 2 3 4
2. %in%
It checks whether and element belongs to other vector
e.g:
>v1 <- 8
>v2 <- 12
>t <- 1:10
> print(v1 %in% t)
>print(v2 %in% t)
[1] TRUE
[2] FALSE
1. Internal Dataset:
R has internal data sets which can be used for study purpose.
>data() ## It gives the list of internal datasets available.
e.g “women” : Average height and weight of American women.
“ Titanic” : Survival of passengers on Titanic.
“mtcars” :Motor trend car road tests.
>help(data set name) ## It gives the details about the dataset
e.g
> help(“women”)
>f1<-women ## it loads the “women” dataset in variable f1
2. External Dataset:
The external data can also be accessed by R as follows:
_______________________________________________________________________________________________________
42
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
[Link]: This is the generic command which can be used to read comma separated values
files or tab delimited values files. The data set on which you want to work should be in the same
directory where you are working for the R session. To check the directory where you are working
in your R session you can use
>getwd() ## get working directory. It gives you the current working directory
If your data set is present in some different directory then change the directory by
Once the directory is set you can use the [Link] and [Link] command as:
e.g:
>data2<-[Link]("hw1_data_Q1_csv.csv",header=TRUE, sep=”,”) ## “hw1_data_Q1_csv” is
the name of the file.
_______________________________________________________________________________________________________
43
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
OR
>data2<-[Link](“hw1_data_Q1_csv.csv”,header=TRUE) ## The [Link] does not require sep
argument Thus [Link] is more specific used for .csv files and [Link] is more generic and
can be used for .csv as well as .txt files.
Note: If the working directory is not set, R could not find the required dataset. In such cases
you can give complete path in [Link] command instead of only name.
>data1<-[Link]([Link](), header=TRUE)
With this a window will pop up. You can browse you file. Here the file is saved in a object
called data1.
OR
You can use [Link] command
>data1<-[Link]([Link](),header=TRUE,sep=”,”)
Note: The [Link] command is specific for csv files hence no need to mention “sep” argument.
But [Link] is more generic command and hence need to mention the “sep” argument. Here
the data is separated by “,” comma hence mentioned sep argument as comma.
_______________________________________________________________________________________________________
44
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Name: It takes the default name of the object as the file name. You can change this to say
data1.
_______________________________________________________________________________________________________
45
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
Sheet: It selects the first sheet as default sheet. You can select the other sheet by down arrow.
Range: You can give the range of the data which you want to work on.
Max Rows: You can select how many rows you want to work.
Skip: You can skip the rows
NA: You can specify the values which you want to treat like NA values.
Also you can skip the complete variable name by using down arrow in the Data preview so that
the complete variable will be skipped. Here the variable solar is skipped.
Import the data, the code for the corresponding import data will be displayed on the console.
You can add more arguments in it.
[1] 79.1
7. Extract the subset of rows of the data frame where Ozone values are above 31 and Temp
values are above 90. What is the mean of Solar.R in this subset?
>mean(Solar.R[Ozone>31 &Temp>90],[Link]=T)
[1] 212.8
8. What was the maximum ozone value in the month of May (i.e. Month is equal to 5)?
>max(Ozone[Month==5],[Link]=T)
[1] 115
Exercise:
Consider the hair color data. Answer the following questions.
Import the dataset with [Link] command. Then attach the data set with attach command.
1. How many people have brown eye color?
>sum([Link]=="Brown")
[1] 10
_______________________________________________________________________________________________________
47
For Private Circulation Only
Bansilal Ramnath Agarwal Charitable Trust’s
VISHWAKARMA INSTITUTE OF TECHNOLOGY
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
666, Upper Indiranagar, Bibwewadi, Pune – 411 037
Document is prepared by Department of S. Y. Common Data Science Group
________________________________________________________________________________________________________
>sum(([Link]=="Green")/length([Link]))*100
[1] 10
Boxplot:
Consider iris data
>boxplot(f$[Link])
_______________________________________________________________________________________________________
48
For Private Circulation Only