0% found this document useful (0 votes)
3 views48 pages

Z - Notes - Introduction To R Complete

The document provides an overview of the R programming language and R Studio, detailing their installation processes and functionalities. It explains how to write and execute code in R, manage comments, install packages, and access help resources. Additionally, it includes exercises for users to practice their skills with R and R Studio.

Uploaded by

Srinath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Z - Notes - Introduction To R Complete

The document provides an overview of the R programming language and R Studio, detailing their installation processes and functionalities. It explains how to write and execute code in R, manage comments, install packages, and access help resources. Additionally, it includes exercises for users to practice their skills with R and R Studio.

Uploaded by

Srinath
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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
________________________________________________________________________________________________________
What is R?

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.

It is available from the Comprehensive R Archive Network, also known as “CRAN”.

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…

It is available as open-source and also as commercial. It has two editions:

1. Desktop Version
2. Server Version.
How to install R?

Step 1: Go to link [Link]

Step 2: Click on the option Download R 4.0.1 for Windows

_______________________________________________________________________________________________________
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.

How to download R studio?

Step1: Go to link [Link]

Step 2: Click on the appropriate option.

_______________________________________________________________________________________________________
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.

Where to write the code?

_______________________________________________________________________________________________________
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
________________________________________________________________________________________________________

2. Source(CTRL+SHIFT+S)/Source with Echo(CTRL+SHIFT+ENTER):


Both the options execute the complete file. The only difference is Source displays the output in
the console window whereas Source Echo displays all the statements along with the output in
the console.
How to make any statement “Comment”?

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.

In R Comments can be given as:

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.

How to install new packages in R?

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.

For example, to install the dslabspackage

>[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
________________________________________________________________________________________________________

Select all the default settings while installing the package.

_______________________________________________________________________________________________________
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
________________________________________________________________________________________________________

Once the package is installed it can be used in R session by command

library(package_name) ie. library(dslabs)


_______________________________________________________________________________________________________
12
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 package remains installed and only needs to be loaded in R session by library command. Once
loaded remains till you quit R session. If you try to load a package and get an error, it probably
means you need to install it first.

We can install more than one package at once by feeding a character vector to this function:

[Link](c("tidyverse", "dslabs"))

Note: To save all the objects/variables you can use

>[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.

How to get help in R?

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).

You can also get the whole document by typing

>[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:

1. Install R and R studio on your Laptop.


2. Create one folder of your name on your D drive. All the lab assignments will be saved in this
folder.
3. Create a R script and write a code to initialize the variables l,m and n with your birth date,birth
month and birth year. Then concate these three variables and save the result in DOB variable.
Print result DOB. (Hint: To concate the three variables you can use the command -- c(l,m,n).)
Save this code with file name as your roll no for example if your roll number is 30 then save
the file as “rn0_30”.
4. Practice the different options as commenting the statements, changing the values of
variables, use of run, source, source Echo.

[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
________________________________________________________________________________________________________

Rules for the names of variables:


1. Allowed characters are alphanumeric characters, ‘_’ , ‘&’ , ‘.’
2. It can start with alphabets. It can also start with ‘.’ But then should not be followed by
number.
3. No special character like ! , @ ,#, $ etc are allowed.
For example:
Valid Name Invalid Name
B2=5 2b=5
.adb=4 .3adb=3
[Link]=4 as@g=1
[Link]=10 d_!=2

R contains some predefined constants like


> pi
[1] 3.141593
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y"
"z"
> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W"
"X" "Y" "Z"

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
________________________________________________________________________________________________________

You can also convert the type of the data as follows:


as.data_type(variable_name)

1. Logical Type: It has two values “ TRUE” and “FALSE”.


For example:
> w=5 > 2
> class(w)
[1] "logical"
>w
[1] TRUE
Here the value of w is TRUE and its class is logical.

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

[Link] sequence operator:


e.g:
>w=seq(2,20,4)
>w
[1] 2 6 10 14 18

3. Using Concatenation command:

>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

Numbers are considered as character if any one element is character.

4. Using rep command:

>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

Accessing vector elements using position:


Vector index in R starts from [Link] vector elements can be accessed by their position as
follows:
For example:
❖ With position
>p=c("jan","feb","mar","apr","may","june","july","aug","sept","oct","nov","dec
")
> print(p)
[1] "jan" "feb" "mar" "apr" "may" "june" "july" "aug" "sept" "oct" "nov"
"dec"
> a<-p[1]
## Square bracket is used to access the element.
>a
[1] "jan"
> c<-p[c(1,2)]
>c
[1] "jan" "feb"

>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

❖ With Negative index


Giving a negative value in the index drops that element from result

>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.

❖ With logical operators

The vector element can be accesses with logical index.


>p[c(TRUE,FALSE,TRUE)] ## Not mentioned positions are considered by default
as true and are displayed.
[1] "jan" "mar" "apr" "june" "july" "sept" "oct" "dec"

> 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.

Manipulating the vectors:

Finding the length of vector:


>q
[1] 1 2 3 4 5 6 7 8 9 10 11 12
> length(q)
[1] 12

Sorting the Vector


## By default the sorting is carried out in ascending order. To sort in
descending order:

>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

Finding the Maximum minimum and mean value of a vector


>s< - -13:19
>max(s)
[1] 19
>min(s)
[1] -13
>mean(s)
[1] 3
_______________________________________________________________________________________________________
23
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
________________________________________________________________________________________________________

Performing operations on vector


>v1<-c(2,3,6,7,9,10)
> v2<-c(1,4,8,2,3,11)
> v1+v2 ## Addition
[1] 3 7 14 9 12 21
> v1-v2 ## Subtraction
[1] 1 -1 -2 5 6 -1
> v1*v2 ## Multiplication
[1] 2 12 48 14 27 110
> v1/v2 ## Division
[1] 2.0000000 0.7500000 0.7500000 3.5000000 3.0000000 0.9090909
> v1%%v2 ## Gives the remainder
[1] 0 3 6 1 0 10

Evaluating powers of vector elements:

>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:

1. Create a vector of numbers 1, 4, 7, 10, 13… 37 by using seq() function.--->


x<-seq(1,37,3)
2. Create a vector of numbers 5 repeated 10 times by using rep() function.---
x<-rep(5,10)
3. Suppose that x and y are two vector containing elements 1, 5, 2 and 3, 7, 9
respectively
i. Augment x by adding y to the left ---c(y,x)
ii. Augment y by adding elements 4, 3, 2 at end—c(y,4,3,2)
iii. Print the maximum value of Y and minimum value of x.-- max(y)
min(x)

_______________________________________________________________________________________________________
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]

LISTS: Unlike vectors, lists can have elements of different types.

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

[[2]] ## second element of list m


[[2]][[1]] ## first element of second list
[1] 1 2 3
[[2]][[2]] ## second element of second list
[1] TRUE
[[2]][[3]]
[1] FALSE

> length(m) ## list m contains two elements i.e f


and s
[1] 2
> length(s)
[1] 3 ## list s contains three elements
> length(f)
[1] 3 ## list f contains three elements

Accessing the list:


List can be indexed with the help of [[]] operator. [[]] is member access.
For example:
>s
[[1]]
[1] 1 2 3
[[2]]
[1] TRUE
[[3]]
[1] FALSE

> s[1] ## accessing the first element of list s [] list slicing.


[[1]]
[1] 1 2 3

_______________________________________________________________________________________________________
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

Naming the elements of list:


The elements of list can be named and then those can be accessed with their
names.
For example:
>ls1<-list(a=1:5,b=c("red","blue"),d=c(T,F,T))
> ls1
$a
[1] 1 2 3 4 5
$b
[1] "red" "blue"
$d
[1] TRUE FALSE TRUE

## To get a particular column


>ls1$a ## accessing the complete first element of the list
[1] 1 2 3 4 5
>j<-ls1$a[4] ## accessing the 4th element of first element of list
>j
[1] 4

Modifying the list:


The list can be modified without reloading the elements. You can modify a
particular element without disturbing the other elements.
For example:
Let us say we want to modify the 4th element of $a to 6 i.e 4 to be replaced by
6.
>ls1$a[4]=6
>ls1$a
[1] 1 2 3 6 5

_______________________________________________________________________________________________________
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).

Creating the matrix:


[Link] function:
A matrix can be created by “matrix” function as follows:

## 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

[Link] and rbind function:


Matrix can be created using cbind and rbind function as follows:
[Link]: The elements are placed columnwise.
>v<-c(3,5,6,6,7)
> w<-c(4,7,8,9,0)
> m<-cbind(v,w)
>m
vw
[1,] 3 4
[2,] 5 7
[3,] 6 8
[4,] 6 9
[5,] 7 0

_______________________________________________________________________________________________________
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

2 Accessing the Matrix:


For a given matrices any one element or any one complete row or column can
be extracted as follows:
>m<-matrix(1:16,4,4)
>m
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
> z<-m[4,3] ## Gives 4th row 3rd column element
>z
[1] 12
> s<-m[,3] ## Gives all rows and 3rd column element
>s
[1] 9 10 11 12
> q<-m[1,] ## Gives 1st row and all column elements.
>q
[1] 1 5 9 13

[Link] with Matrices:


>a<-matrix(1:4,2,2) ## declaring the matrix a
>a
[,1] [,2]
[1,] 1 3
[2,] 2 4
> b<-matrix(5:8,2,2) ## declaring the matrix b
>b
[,1] [,2]
_______________________________________________________________________________________________________
32
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,] 5 7
[2,] 6 8
> c<-a+b ## adding two matrices
>c
[,1] [,2]
[1,] 6 10
[2,] 8 12
>d<-a-b ## subtracting two matrices
>d
[,1] [,2]
[1,] -4 -4
[2,] -4 -4
>e<-a*b ## Element by element multiplication
>e
[,1] [,2]
[1,] 5 21
[2,] 12 32
>f<-a%*%b ## Matrix multiplication
>f
[,1] [,2]
[1,] 23 31
[2,] 34 46

>t(f) ## Gives transpose of matrix


[,1] [,2]
[1,] 23 34
[2,] 31 46
> solve(a) ## Gives inverse of matrix.
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5

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:

1. Create the matrix A and B with values as shown below:

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).

Creating Data Frame:


Consider the following data from website ESPN cricinfo live
Name Matches Innings Highestscore average
Tendulakar 200 329 248 53.78

_______________________________________________________________________________________________________
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

Getting summary of data in data frame:


The summary of data in data frame cab be obtained by function summary().
>summary(match_stat)
name matches innings highestscore
avg
cook :1 Min. :161.0 Min. :280.0 Min. :224.0 M
in. :45.35
Dravid :1 1st Qu.:164.0 1st Qu.:286.0 1st Qu.:248.0 1
st Qu.:51.85
kallis :1 Median :166.0 Median :287.0 Median :257.0 M
edian :52.31
Ponting :1 Mean :171.8 Mean :294.6 Mean :258.6 M
ean :51.73
_______________________________________________________________________________________________________
36
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
________________________________________________________________________________________________________
Tendulkar:1 3rd Qu.:168.0 3rd Qu.:291.0 3rd Qu.:270.0 3
rd Qu.:53.78
Max. :200.0 Max. :329.0 Max. :294.0 M
ax. :55.37

Accessing data from data frame:


The data from the data frame can be accessed as follows:

[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

Adding New columns:


Any new column can be added in the data frame given as below. Let we want to add number o
f 50s and 100s for every player of the data frame. We use ‘$’ operator to introduce
>match_stat$half_cent<-c(68,62,58,63,57)
> match_stat$cent<-c(51,41,45,36,33)
> match_stat
name matches innings highestscore avg half_cent cent
1 Tendulkar 200 329 248 53.78 68 51
2 Ponting 168 287 257 51.85 62 41
_______________________________________________________________________________________________________
37
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
________________________________________________________________________________________________________
3 kallis 166 280 224 55.37 58 45
4 Dravid 164 286 270 52.31 63 36
5 cook 161 291 294 45.35 57 33

Adding New rows:


New rows can be added in the existing data frame. Let we want to add two more players Sang
akkara and Lara. This can be done by rbind function.
>new_match_stat<-[Link](name=c("sangakkara","lara"),matches=
c(134,131),innings=c(233,232),highestscore=c(319,400),avg=c(57.4,
52.8),half_cent=c(52,48),cent=c(38,34))
> match_stat<-rbind(match_stat,new_match_stat)
> match_stat
name matches innings highestscore avg half_cent cent
1 Tendulkar 200 329 248 53.78 68 51
2 Ponting 168 287 257 51.85 62 41
3 kallis 166 280 224 55.37 58 45
4 Dravid 164 286 270 52.31 63 36
5 cook 161 291 294 45.35 57 33
6 sangakkara 134 233 319 57.40 52 38
7 lara 131 232 400 52.80 48 34

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

Exercise: Refer the table given above with five players.

1. What is the highest score of Tendulkar?


>match_stat[which(match_stat$name=="Tendulakar"),4]
[1]248
2. Display the name and the average of the player who is having maximum highestscore.
_______________________________________________________________________________________________________
38
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
________________________________________________________________________________________________________
>match_stat[which(match_stat$highestscore==max(match_stat$highes
tscore)),c(1,5)]
name avg
5 cook 45.35
[Link] the name,matches,innings and average of the players having score above 250.
>match_stat[which(match_stat$highestscore>=250),c(1,2,3,5)]
name matches innings avg
2 Ponting 168 287 51.85
4 Dravid 164 286 52.31
5 cook 161 291 45.35
4. Find the row number of the data for which the highestscore is equal or greater than 270
>which(match_stat$highestscore>=270,[Link]=T)
[1] 4 5
5. Modify Tendulkar’s number of matches as 201.
>match_stat[match_stat$name=="Tendulakar",2]<-201

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.

It gives result in terms of Boolean value TRUE or F


ALSE

[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

Working on the datasets

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

>setwd(“path name”) command.


e.g:
>setwd("D:/abha/R_programming/course") ## here the directory called as “course contains
the dataset. It sets the working directory.
OR
Go to Tab ---Session→ set working directory→choose directory

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.

Following command can also be used to access the dataset:


[Link] CSV files:

>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.

[Link] .xls and .xlsx files:


The excel files can be imported as shown below

_______________________________________________________________________________________________________
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.

Exercise: Consider the pollutant data.


1. What is the mean of “Temp” when “Month” is equal to 6?
>setwd("D:/subjects_modi_27_7_16-2016-07-27/subjects_modi_27_
7_16/Data Science/RData sets")
>f<-[Link]("pollutant_csv.csv",header=T)
>attach(f)
> mean(Temp[Month==6])

[1] 79.1

2. How many observations are there in the given data?


_______________________________________________________________________________________________________
46
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
________________________________________________________________________________________________________
>nrow(f)
[1] [153]

3. Print last two rows of the data.


>tail(f,n=2)

4. What is the value of Ozone in 47th row?


>a<-Ozone
>a [47]
[1] 21
OR
>f[47,1]
[1] 21
5. How many values are missing in Ozone column?
>a<-Ozone
>length(a[[Link](a)])
[1] 37
6. What is the mean of Ozone column excluding missing values?
>mean(Ozone, [Link]=T)
[1] 42.12931

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
________________________________________________________________________________________________________

2. How many people have Blonde hair?


>sum([Link]=="Blonde")
[1] 6

3. How many Brown haired people have Black eyes?


>sum([Link]=="Brown" & [Link]=="Black")
[1] 2

4. What is the percentage of people with Green eyes?

>sum(([Link]=="Green")/length([Link]))*100
[1] 10

5. What percentage of people have red hair and Blue eyes?

>d<-sum([Link]=="Red" & [Link]=="Blue")


> per<-(d/length([Link]))*100
> per
[1] 5
Experimtent 1 Data Visualization

Boxplot:
Consider iris data
>boxplot(f$[Link])

_______________________________________________________________________________________________________
48
For Private Circulation Only

You might also like