R Programming 1
R Programming 1
UNIT II
VARIABLES
Basico fR
SR
launch the R interpreter with a symbol likc this > and you start
This comnmand
nd will let you
program
Using comma prompt:
the
W 7tng
-
World!"
"Hello
newStr
print(newStr)
" H e l l o - World!"
Script:
«. "Hello, World!"
myString
SRscripttest.R)7A
COMMENTS IN R PROGRAMMING
statemecnts get ignored by
source code
and thesc with
text within ourR is wrilten
line comment
Omments are like helping program.
The single
while running
nlerpreter your actual below:
e the statement as given
ne
starting symbol #' in the beginning of
**
-- -------********* *****
*****-
Another Example
in R
ss
doc s something completcly different to c and
K
The c1
function
programming. Example:
they arc
frequently uscd in
#look, no loops!
1:4 + 5:8
68 10 12 14
will be: [|]
## Output
c(0, 1, 5, 7, 9)
c(1.
26,8, 10)+
| 1 | T 3 1 |15 19
be:
##Outputwill and
and the
the cc function
function are used alimost
The colon
operator
practice using them.
everywhere in R code, so it's good to
VARLABLES
What isaVariable?
riables are used to store information to be
referenced and manipulated in a
computer program.
Variable Assignment
C variables can be assigned values using leftward, rightward and equal to operator.
T Values of the variables can be printed using print() or cat()function.
E
Cal) function combines multiple items into a continuous print output
*ASSIgnment using equal operator.
var.= c0,1,2,3)
it produces the
p r o d e .
above
ade. it
code,
following result
the
e x e c u t e
we
When
i]0123
Var.I is O123
lcam
R
ar.2 is
Var.3i s I1
Variable
Tvpeofa1 r r a b l e i t s c l t
is notnot declared
declaro.
of any data
type, rather it gets the data
Data it. type of
In R. a assigned
to
the R-
object
a namically typed language, which
is called pe of the same variable again and againmeans that it incan
ariable
So R 'sdata when usingwe a program. a change
Live Demo
1ar_ "Hello"
"The
class ofvar_X
is class(var_x),"n"
cat
ar_ j45
class of var_x
1s ",class(var_x),"n")
cat Now the
ar_127L
ext the class ofvar_x becomes ",class(var_x),"n")
cat
character
The class of var_x is
numeric
Now the class of var_x is
Next the class of var_x becomes integer
REMOVING VARIABLES
remove and rm can be used to remove objects.
in the character vector list,
These can be specified successively as character strings, or
FALSE)
FALSE)
mp - 1:4
Ork with tmp
m{tmp) and cleanup
Not run.
Temove (almosteverythine
) in the working environment.
****** -~-----.
## You will get no warning, so don't do this unless you are really sure.
Im(list = Is())
## End(Not run)
DATA TYPES:
S as.integer(3)
# print the value of s
Warning message
In sqrt(-1):NaNs produced
A logical value is mostly created when comparison between variables are done. Example will
be like:
a = 4; b = 6
#sample values
ga>b # is a larger than b?
Output
[1] False
g as.character(62.48)
Output
1] "character"
R-VECTORS
Meaning of vectors:
Vector is a basic data suucture n R
I t contains elenent of the same type.
The data types can be logical. integei, double, character, complex or raW
A vector' s type can be checked with the typeol) niction.
Another inportant property of a vector is its
leugtlh
This is the number of clenents in the vector and can be checkcd with the
function length().
Vectors are the most basic R data obiects and there are six types of atomic vectors.
EXAMPLE
# Atomic vector of type character.
print "abec"):
# Atomic vector of type double.
print 12.5)
#
Atomic vector of type logical.
print TRUE)
Atomic vector of type complex.
print 2-3i)
ALomic vector of type raw.
print charToRaw('hello'))
when we execute the above code, it produces the following result
]"abe"
[1] 12.5
(]63
[] TRUE
2-31
1 6% 65 6c 6c 6f
# the final clement specilicd does not belong to the sequence then it is disciarded.
v3.8:11.4
print(v)
-----
****----------------------
-------
execute
the abov code, it produces the followi result -
When we
5 6 7 8
1011 12 13
9
[1] 9.6 10.6 11.6
12.6
] 6.6 7.6 8.6 9.8 10.8
6.8 7.8 8.8
1] 3.8 4.8 5.8
operator
Using segquence(Seq.)
it
execute the above code, produces
the following result-
When we
converted to characters.
#The logical and numeric values are
sc('apple', red',5,TRUE)
print(s)
When we execute the above code, it produces the following result-
1] "apple" "red" "5" "TRUE"
#
A.ccessing vector elements using posilion.
C'Sun"."Mon","Tue" "Wed""Thurs","Fri"."Sal")
u-cl2.3.6)
printu
V E C T O R MANIPULATION
Yector arithmetie can ibe added, subtracted, multiplied or divided giving the result
of s a i m e length
Two vectors
as a vector output.
Examples:
#Create twovectors.
ll3S4.S.0.11)
2-c4|,0.8,1.2)
# Vector addition.
add.result <vl-v2
print add.result)
# Vector subtraction.
sub.result vl-v2
printí sub.result)
#Vector multiplication.
muli.result<vl*v2
printi multi.result)
Vector division.
divi.result -vl/v2
print divi.result)
When we execute the above code, it produces the following result
1] 719 413 1 13
1]-1-3 4-3-19
[1 12 88 040 0 22
[1]0.75000000.7272727 Inf 0.6250000 0.0000000 5.5000000
v-c(3.84,5,0,11)
2-c4,1
# V2
becomes c(4,11,4,11,4,1))
addresult- vl v2
printadd.result)
sub.result<- vl-v2
print(sub.result savc code. it produccs the following result
above
the
e x e c u t e
Vhen w We
422
719
]-1-3 0-6-4 0
8 16
Vector ElementSorting
can
orted
be sort. using the sort() funct
vector
ments in a
304)
45.0,11. -9,
c(3,8
vector.
of the
Sort the elements
Sort.result~-sort(V}
print sort.resulti
printrevsort.result)
e "Red"."Blue"."yellow"."violet")
sortresult sort(v)
print sort.result)
print revsSort.result)
When we execute the above code, it produces the following result
[] -9 0 3 4 5 8 11 304
[11 304 11 8 5 4 3 0 -9
] "Blue" "Red" "violet" "yellow"
1 "yellow" "violet" "Red" "Bluc"
R-OPERATORS
MEANING
An
operator is a
symbol that compiler to perform specitic
tells the
mathematical or logical
of
anguage is rich in built-in operators and provides folloWing types
operatorS.
Types of Opcrators
We have he
following
types of operators 1n k
Arithmetic Operators pio8
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
Arithmetic
An
Operators
arithnetic operator isa mathematical function that takes two operands and performs a
calculation mathematical
them. They re
on
a
lunc arithmetic and most computer languages
used in common are used in com
*******
a n be u
uscd
e
wilhin cquations to perform a number of
erators that
operatoOrs
can
thal c
such
sct of
Contain a c a l c u l a t i o n .
scqucntial
Vpes of
Description
Operator
Addition
Subtraction
Multiplication
Division
Exponent
Modulus (Remainder from division)
Integer Division
/%
Relational Operators
Opepalors Meantnga Eonpe Resm
False
Less than 52
Grcater than S2 Tiue
Less than or 5<-2" False
cqual to
(ircater than 52 Truc
oT cqual to
Equal to -2 F'alse
Not equal l 51 -2 Tue
www.geekyshows.con
Lopical Operators
I t 1s applicable only to vectors of t ype logical,
numeric or C nplex.
All numbers grealer than 1 arc considered as logical value l UE.
Each clement of the first vector is compared with the corresponding clement ofthe
Second vector, The result
of comparison is a Boolean viu
Operator Description
Logical NOT
Logical ANID
Element-wise logical OR
Logical OR
Assignment Qperators
and can be used, almost interchangeably, to assign to variable in
The operators S-
=
the s m e environment.
The operator is used for assigning to variables in the parcnt environments (morc
like global assignments).
The rightward assignments, although available are rarely used.
Operator Description
4, Leftwards assignment
ADVANCEDDATA STRUCTURE:DATA.FRAMES
R-DATA FRAMES
da lrane is a lable or a two-dinensional aay-likestrucliie m whiwh each colunu
Cofilais Valucs of oie Vanable and cach 1oW contams one set ol vilues tron each colu
***********
in a data frame can beof numeric, lactor oor character type.
The data stored contain same number of data items)
Each column
should
emp_id=c(1:5),
"Gary")
cmp nane
s a l a r y =
=c("Rick","Dan"."Michcllc","Ryan",
c ( 6 2 3 . 3 . 5 1 5 . 2 , 6 1 1 . 0 , 7 2 9 . 0 , 8 4 3 . 2 5 ) .
start date =
as.Datc(c("2012-01l-01", "2013-09-23", "2014-11-15", "2014-05-11"
"2015-03-27").
strngsAsFactors = FALSE
#
Print the summary.
print(sunmary(emp.data))
emp_name =
c("Rick","Dan"
salary "Michelle","Ryan","Gary"),
c623.3,515.2.611.0,729.0,843.25).
When we
execute the resunt
bo above
v e code,
co it produces the followig
emp.uala.Rick
emp namc emp.data.Sülary
623.30
--------------
-- *****--********-*- ************-****-*-
-----------------****
515.20
Dan
611.00
Michelle
729.00
4 Ryan
843.25
Gary
"2014-05-1|"
Slart datc =as.Date(c("2012-01-0, "2013-09-23", "2014-11-15",
"2015-03-27").
StringsAsFactors = FALSE
Extract 3rd And 5th Row With 2nd And 4th Column
Create the data frame.
emp.data-data.frame(
emp_id=c (1:5),
emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
salary c(623.3,515.2.611.0,729.0,843.25),
start_date = as.Datc(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11".
"2015-03-27"),
stringsAsFactors = FALSE
#Extract 3rd and 5th row with 2nd and 4th columin.
resull- cnp.data|c(3,5),c(2,4)]
prntresult)
wlCH
WE excule thc above code, it Droduces the lollowillE
emp_naine start date
3 Michclle 2014-11-15
5 Gary 2015-03-27
Expand
A
Data Frame
data frame rows.
be expanded by adding columns anl
can be
an
---------
name.
column
new
a
Add Column vector
using
column
Just add the
data frame
# Create the
cmp.data<-data.frame
"."Michelle", "Ryan", "Gary").
Salary=c(623.3,51.5.2.611.0,729.0.843.25),
Cmp_id=e(1:5).
1ame= c("Rick"."Dan"
emp "2014-05-11".
"2014-11-15".
"2013-09-23",
Date(c("2012-01-01°,
couln. "Finance")
"dept" "IT","HR",
# Add the "Operations",
emp.dataSdept
<- c("IT",
emp.data
print(v)
following result
-
it produces the
we e x e c u t e
the above code,
When
salary start_date dept
emp_id emp_name
623.30 2012-01-01 IT
1 Rick 515.20 2013-09-23 Operations
2 Dan IT
Michelle 611.00 2014-11-15
729.00 2014-05-11 HR
4 Ryan 2015-03-27 Finance
843.25
Gary
"2015-03-27" )),
dept
TT,"Operations"
stringsAsl actors FALSE "I" "{R","Finance ).
#Create he
emp.newdatasecond
< data frame
cmp d (6:8),data.frame
c
c("Rasmi,"Pranab","Tusar")
=
emp nanme
salary = c(578.0,722.5,632.8),
stringsAsFactors = FALSE
fiames.
#Bind thc two data
emp.tinaldata *- rbind(emp.data,cmp.newdata)
print(emp.linaldata)
R-LISTS
R language provides programmers with the facility to put elements of different types
into a single container like numbers, strings, vectors etc.
This flexibility of containing multiple types of elements is possible s R proyramming
using Lists.
A list, in lame word, a vector in which all the element can be of a diverse type.
t can be handled by first creating lists then using index programmers can manipulate
ists
LISts can be created using the list function and denoting the contents works a lot like
MATRIX
s a two-dimensional data structure and can be ercated usng matix )
function.
dlues for rows columns can be detined using nrow and ncol argunes.
Ilow
prviding both is not required as other dimension is automatically taken
With the
hclp of length of malurIx.
aist
list (p . I y," 91, 6)
" ,, c(12, 9 , 0 ] i ,
c(12, 19, 0'' FALSE,
**.
*****------------
print (alist)
e r e alist is the name or he list, Iist() is use to lists all the elements of different
c And the next is the print statement which prints the entire variablec's value.
ypcs.
Variables
Atomic and Recursive
D u e to this capability or COntaining other lists within themselves (lists). lists are
The functions is.recursive and is.atomic let programmers' test variables to scc what
For example,
3 6 9>
1 4 7[2.1 2 5 8[3,]
matrix(1:9, nrow =3, ncol =3) [,1][2] [.3][1,] nrow =
3) 1,J12J
dimension> matrix(1:9,
Same result is obtained by providing only one
3I[.] 4 712.] 2 5 8[3,1 3 6 9
first 2
second 4.
third list
fourth 3.2.
fifth 6.4
aCCess eevery
you
verv
elcment of the list by the
ma n a c c e s s
c
As with
vectors,
use of
indices ar
o r using clement names or by the
using element square brackets [1.
logical index. Here is an
-
numeric
and by
how o
values
use
these example of
Is | 1:2
# Stirst
#||]2
#Ssceond
[114
s
$ first
1]2
S second
[1]4
Or the lists values can also be invoked using element's name as
s c "irst". "second"))
= S first
1]2
= S second
1]4
+Now you
will remove
the lasl
ast element from thec list
alist 4) NULL CI
#Now you
will
update the 2nd
Elemnent
- - * * * - - * * * * * * * * * * - - * * * * * - - - - - - - - - - - - - - - - - - - - * * * * * * * * * * * * *
*****
alist [2]"Karlos"
print (alist|2|)
dimensions.
This is bccause they have only length but no other structurc.
dimensional rectangular shaped data storage
AITays can contain multi same length and similarly
for each
"Rectangular" in the sense, each row is having the
column and other dimensions.
dimensional arrays.
special type of two
-
Matrices are a
variables / elements
B u t arrays can store only values having similar kinds of data, i.e.
having similar data type.
the array() function.
An array can be created in R language using for
and use the values in the dim parameter
AIrays take vectors in the form of input
Creating an array.
we can also provide names for each dimension:
vecl<-c (3 4, 2)
vec2- c (1l, 12, 13, 14, 15, 16)
#taking these v e c t o r s
as input for this array
r e s l - array (c (vectorl, vector2), dim=c (3,3,2)
print (res1)
MatA
ROWA ROWB ROWC
COLA 211 14
COLB 4 12 15
COLC6 13 16
MatB
ROWA ROWB ROWC
COLA 211 14
COLB 4 12 15
COLC6 13 16
R-MATRICES
Matrices are the R objects in which the clements
ar arrangcd in a two-dimensional
rectangular layout.
They contain elements of the same atomic typcs.
Though we can create a matrix containing only characters
they are not of much use.
or only logical values,
We use matrices
containing nuerie elements to be used in mathematical
calculations.
A Matrix is
created using the matrix() functlion.
Syntax
The basic syntax for
creating a matrix in R is
matrix(data, nrow, ncol, byrow, dimnanmes)
Following is the description of the parameters used
data is the input vector which becomes the data
elements of the matrix.
nrow is the number
of rows to be created.
ncol is the number of colum1ns to be created.
-------
--------*-
**********---------.
byrow is a logical elue. If TRUE then the input vector elements are arranged by row.
dimname is the names assigncd to the rows and columns.
Example
Create a nmatrix taking a vector of numbers as input.
Live Demo
# Elements are arranged sequentially by row.
M- matrix(c(3:14), nrow 4, byrow =TRUE)
=
print(M)
printN)
print(P)
When we execute the above code, it produces the following result-
.1] L2113
[1] 3 4 5
2.] 6 7 8
3.] 9 10 11
14.] 12 13 14
[I][.2] [3]
[1] 3 7 11
2] 4 8 12
[3.] 5 9 13
[4] 6 10 14
coll col2 col3
rowl 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
*********--~~-----.
**********-*******-*****-***--*~-------
print(P[1,3])
# Access the element at 2nd column and 4th row.
print(P[4.2])
# Access
only the 2nd row.
print(P[2.])
#Access only the 3rd column.
print(P[.3})
When we execute the above code, it produces the
following result
[5
] 13
coll col2 col3
67 8
rowl row2 row3 row4
5 8 11 14
Matrix Computations
Various mathematical operations are
performed on the matrices using the R
operators.
The result of the operation is also a matrix.
The dimensions (number of
rows and columns) should be same for the matrices
involved in the operation.
Matrix Addition &Subtraction
#Create two 2x3 matrices.
matrix1 <K- matrix(c(3, 9, -1, 4, 2, 6), nrow =
2)
print(matrix1)
cat("Result of subtraction","\n")
print(result)
When we execute the above code, it produces he lollowing result
][.2] 1.3]
1. 3 12
12 9 4 6
I.][.2] [,3
r----------------***************-***-----------
*********
***-*-***---~----------------------*-****
5 0 3
2.] 2 9 4
Result of addition
I..21 [.3
[1 8 -1
12.1 11 13 10
Result of subtraction
I1]L2][.3]
[1]2-1 -1
2] 7 -5 2
cat("Result of multiplication","\n")
print(result)
# Divide the matrices
result - matrix1 /matrix2
cat("Result of division","n")
print result)
When we execute the above code, it produces the following result -