0% found this document useful (0 votes)
22 views

R Programming 1

This document discusses variables in R programming. It explains what variables are, how they are used to store and label data, and how they are assigned values. It also discusses variable naming conventions and provides examples of assigning values to variables using different operators and printing the values.

Uploaded by

meghasree081
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

R Programming 1

This document discusses variables in R programming. It explains what variables are, how they are used to store and label data, and how they are assigned values. It also discusses variable naming conventions and provides examples of assigning values to variables using different operators and printing the values.

Uploaded by

meghasree081
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

*****************-

UNIT II

VARIABLES

Basico fR

he environncnt lor R, il 1s caSy to start R command prompt by simply


haNC Sctup
nee
ne d mentioned below al your command prompt:
(
y n g the comnand,

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!"

in Script iies and then we implement


those
scripts at our
11a l l write the programs called Rscript. Here is the Hello World
using the help of R interpreter
command prompt

Script:
«. "Hello, World!"
myString

print(myString) command prompt


cxecute this code at Linux
file "helo.R" and
Sane the code
have written in a
command.
below mentioned
using the

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

# My first R program is Hello - World a


but you can pettorm
comment
multi-line
dsadvantagcous that R does not support
like lhIS:
nck and is code will Jook something
if ALSE) comnicnts.
ThiS Is an
example of how to write multi-line

newStr "Ilello - World!"


inside
have to
be put
should
print ( newStr) Multi-line
comment

It is tobe noted that the Strings while using


Cither stringsw
Single quote orCDouble QuoLC
**

**
-- -------********* *****
*****-

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.

hey also provideway of labelling data with a


a
descriptive name, so our
can be understood more clearly by the reader and ourselves. programs
Itis helpful to think of variables as containers that hold information.
Their sole purpose is to label and store data in memory.
This data can then be used throughout your program.)10A
R-Variable
A variable provides us with named storage that our programs can manipulate.
A Yariable in R can store an atomic vector, group of atomic vectors or a combination
of many Robjects.
Avalid variable name consists of letters, numbers and the dot or underline characters.
The variable name starts with a letter or the dot not followed by a number.) 6A

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)

arASsignunent using leftward


2-c"learn","R") operator.
t#
Assignment usingrightward operator.
CTRUE, I) ->var.3 rightwa
prin("var.l
Cat t(var.I)
Cat var.2 isis", var.1 "\n")
Cat('var.3 is",", var.2 ,"\n")
var.3 ,"\n")
--********
---------

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

hen we execute the above code, it produces the following result -

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

or through a combination of both.


All objects thus specified will be removed.
l f envir is NULL then the currently active environment is secarched tirst.
variable
the supplied directory are searched until
a
merits TRUE then
is of
parents
wth the
given name is encountered.
A is printed for each variable that is not found.
Usage
emove... ist=
Cnvir = as. character(), pos =
-,
FALSE)
ironment(pos), inherits =

character(), pos= -1,


envi
Exarmples
r=as.environment(pos),
ument(pos), inherits
=

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:

several basic data types in R which are of frequent occurrence in coding R


calculations and programs.

Here is the list of all the data types provided by R:


Numeric
Integer
Complex
Logical
Character 5A
Numeric Data type
Decimal values are referred as numeric data types in R.
T h i s is the default working out data type. If we assign a decimal value for any variable x
like given below, x will become a numeric type.
g62.4 assign a decimal value to g

#print the variable's value -g

Integer Data tvpe


1 1 w e want to create any integer variable in R, you have to invoke the as.integer() function

to define any integer type data.


the is.integer() function.
We can be certain that y is definitely an integer by applying

S as.integer(3)
# print the value of s

as.integer(3.14) drives in a numerie value


toi,
ut it will work like type casting where the value of 3. 14 gets changed

Complex Data ipe


A COmplex valuc for codinu in R can be detined using the pure imagary values T

k1+21 # ccating a complex number

it printan te value ofk

sce s o l i COlpiex \ilue


h e below ienoned
cxidple i v e s a n cITor
Sqrt(-1) # square root of-1

An the eTor message will be something like this:

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?

# print the logical value

Output
[1] False

Character data type


A character object can be used for representing string values in R.
We have to convert objects into character values using the as.character() function within your
code like this:

g as.character(62.48)

e #prints the character string


Output:
) "3.14"
class(s) # print the class name of s

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.

Thev are logical, integer, double, complex, character and raw


Yector Creation
Single Element Vector
Fven when you writc just one value in R, it becomes a vector of lengthl and belongs to one

of the above vector types.

EXAMPLE
# Atomic vector of type character.

print "abec"):
# Atomic vector of type double.
print 12.5)

# Atomic vector of type integer.


print63L)

#
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

Multiple Elements Vector


Using colon operator with numeric data
# Creatung a
sequence from 5 to 13.
V-S:13
print'V
#
Creating a sequence from 6.6 to 12.6.
v66:12.6
printv)

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

# Create vector with


elements from 5 to 9 incrementing by 0.4.
print(seq(5, 9, by 0.4))
=

it
execute the above code, produces
the following result-
When we

7.0 7.4 7.8 8.2 8.6 9.0


1]5.0 5.4 5.8 6.2 6.6

Using thec) function character.


The non-character values are coerced to character type if one of the elements is a

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"

Accessing Vector Elements


Elements of a Vector are accessed using indexing.
starts with position 1.
The [ ] brackets are used for indexing. Indexing the index drops
that element from
value in
Giving a negative
result.TRUE, FALSE or 0 and 1 can also be used for indexing.

#
A.ccessing vector elements using posilion.
C'Sun"."Mon","Tue" "Wed""Thurs","Fri"."Sal")
u-cl2.3.6)
printu

#ACcessing vector elements using logical indexng.


V CRUEFALSE FALSE.FALSE.FALSE.TRUE.FALSE)|
prinv

# Accessing vector clements using negative mdexng


x1ct-2..5)
printíx)
i# Accessing vector clements using 0/I indexm
ytc(0.0.00.0.0,
printy)
When we execute the above code, it produces the following result
"Tue" tri
"Mon"
]
0 "Sun" "Fri "Fri" "Sat"
"Wed"
"Tue"
1] "Sun"
] "Sun"

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

Vector Element Recvcling


aPpy arithmetic operations to two vectors of unequal
shorer vector
are
recycled to complete the operations. length, then the elements of the

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

the reverse order.


#Sort the elements in
TRUE)
revsort result sort(v. decreasing
=

printrevsort.result)

Sorting character vectors.

e "Red"."Blue"."yellow"."violet")
sortresult sort(v)
print sort.result)

Sorting character vectors in reverse order.


Tesort.result- sort(v. decreasing = TRUE)

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 operator language construct


In computer science, a relational operator is a programming
relation between two entities. These include
or operator that tests or defines some kind of

numerical equality (e.g., 5 5) and inequalities (e.g., 4> 3).


-

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

& Element-wise logical AND

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

->, ->> Rightwards assigniment


Miscellaneous Operators
These operators does not fall into any of the categories mentioned above. but are signiticantly

important during Rprogrammingfor manipulating data.


Operalor Description Usage

Creates series of numbers from left operand to right operand a:b

ino Tdentifies if an clement(a) belongs lo a vector(6) a oino b

Performs multiplication of a vector with its transpose A *%t(A)

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

Following arc the charaetenstics of a dat Iranic


The coluimn names should be non-vmpty
The row names should be unique

***********
in a data frame can beof numeric, lactor oor character type.
The data stored contain same number of data items)
Each column
should

Create Data Frame


# Create the data frame.
emp.data <- data.frame(

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


print(emp.data)

When we execute the above code, it produces the following result-

emp_id emp_name salary start_date


Rick 623.30 2012-01-01
Dan 515.20 2013-09-23
Michelle 611.00 2014-11-15

Ryan 729.09 2014-05-11


Gary 843.25 2015-03-27

Get theStructure of the Data Frame


The structure of the data frame can be seen by using str() function.

#Create the data frame.


emp.data- data.frame(
emp_id= e (1:5),
emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
salary c623.3,515.2,611.0,729.0,843.25),
Start date as.Date(c("2012-01-01"
=
"2013-09-23", "2014-11-15", "2014-05-11".
2015-03-27"))
stringsAsFactors=FALSE

# Get the structure of the data franme.


str(emp.data)
When we execute the above code, it produces the following resun
'data.frame': 5 obs. of 4 variables:
S emp_id int 1 2345
S emp_name : chr "Rick" "Dan" "Michelle"
"Ryan" .
S salary num 623 515 6l1 729 843
$ start date: Date, format: "2012-01-O 2013-09-23" "2014-11-15" "2014-05-1T°
Summary of Data in Data Frame
and nalure of the data can be obtained
The statistical summaryy
by
applying summary(O function.

# Create the data frame.


cmp.data <- data.frame(
Cmp_id=c(1:5).
emp name =e("Rick"."Dan"."Michelle","Ryan","Gary")
salary=c(623.3,515.2,611.0,729.0,843.25),

start date=as.Date(c("2012-01-01", "2013-09-23", "2014-I1-15", "2014-05-11".


"2015-03-27").
stringsAsFactors = FALSE

#
Print the summary.
print(sunmary(emp.data))

When we execute the above code, it produces the following result-


emp_id emp_name salary start date
Min. :1 Length:5 Min. :515.2 Min. :2012-01-0i
Ist Qu.:2 Class :character 1st Qu.:611.0 1st Qu.:2013-09-23
Median:3 Mode :character Median :623.3 Median:2014-05-11
Mean :3 Mean :664.4 Mean :2014-01-14
3rd Qu.:4 3rd Qu.:729.0 3rd Qu.:2014-11-15
Max.:5 Max. :843.2 Max. :2015-03-27

Extract Data from Data Frame


Exiract specific column from a data frame, using column name.

#Create the data frame.


emp.data - data.frame(
emp_id = c(1:5),

emp_name =

c("Rick","Dan"
salary "Michelle","Ryan","Gary"),
c623.3,515.2.611.0,729.0,843.25).

216as.Datefe("2012-01-01" 2013-09-23" "2014-1U-15""2014-05-1


201503-27" ).
sung AsFactors ALSE
#
Exract
Specific columns.
Tesult

prntreull) Cmp.dataSemp ame,emp.dauaSsalary)

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

And Then All Columns


tract The First Two Rows
# Create the data firame.
Cmp.data<-data.fiame(
Cp_id=e(1:5), "Ryan" "iary
nanne
cmp c("Rick"."Dan", "Michelle",
S a l a r y c ( 6 2 3 . 3 . 5 1 5 . 2 . 6 1 1 . 0 , 7 2 9 . 0 , 8 4 3 . 2 5 ) ,

"2014-05-1|"
Slart datc =as.Date(c("2012-01-0, "2013-09-23", "2014-11-15",
"2015-03-27").
StringsAsFactors = FALSE

#Extract first two rows.


result- cmp.data|1:2,
printresult)

When we execute the above code, it produces the following result -

emp_id emp_name salary start date


Rick 623.3 2012-01-01
1
2 2 Dan 515.2 2013-09-23

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°,

Stat date =as.


"2015-03-27")).
stingsAsFactors = FALSE

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

Add Row need to bring in the


permanently to an existing data frame, we
To add more rows
structure as the ex1sting data
frame and use
new rowS in the same

the rbind) function.


data frame with new rows and merge it with the
n the example below we create a

existung data frame to create the final data framne.

#Createthe first data frame.


emp.data- data.frame(
emp_id c(l:5),
emp_Dame =e("Rick","Dan" "Michelle"
"Ryan"."Gary"),
salary = ct623.3,515.2.611.0,729.0,843.25),
Start datc as.Datc(c("2012-0LLQ "2013-09-23", "2014-1-15", '"2014-05-11".

"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),

start date =as.Date(c("2013-05-21"."2013-07-30", "2014-06-17").


dept c("IT"."Operations","Fianance"),

stringsAsFactors = FALSE

fiames.
#Bind thc two data
emp.tinaldata *- rbind(emp.data,cmp.newdata)
print(emp.linaldata)

When we execute the above code, it produces the following result -

cmp_id emp_name salary startdate dept


1Rick 623.30 2012-01-01 IT
Dan 515.20 2013-09-23 Operations
Michelle 611.00 2014-11-15 IT
Ryan 729.00 2014-05-11 HR
Gary 843.25 2015-03-27 Financc
Rasmi 578.00 2013-05-21 IT
Pranab 722.50 2013-07-30 Operations
8 Tusar 632.80 2014-06-17 Fianancee

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

he'e function which you have seen already in previous tutorials.


e Just ist the contents, with each argument and cach separated by a comma.
Clenents can be of any variable type-vectors, numbers or even functions.
1ere iS a
simple example of how to use list in K

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

considercd as the rccursive variables,


Vectors and arrays, by delault, come under the category of atomic variables.

Variables can either be recursIve or atomic but neverboth.

The functions is.recursive and is.atomic let programmers' test variables to scc what

their types are. Here is a simple example of using these 2 functions-

is.atomic (list ())

#[] FALSE the output comes as False

is.recursive (list ())

# [ ] TRUE the output comes as True

Is.atomic (numeric (0)

#[] TRUE the output comes as True

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

Consider this test list:


Is-list

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

Manipulating List Elements


We can elements within a list.
insert, delete, update and modify list
We Can
We can nsert and delcte clements just at the end of any list.
But list allows to
update any element.
names'alist)-c("Ray"
"Karl", "Steve
Now you
will add
clement alal the end of the list
CICDIent
slist 4"Mar"
print ialist 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|)

MATRICES AND ARRAYS


memory
to storc and
use
the facility
Rprogramming also provides programmers with
locations in the form of one or more dimensions
That concept is possible with the use of arrays last tutorial arc all
have implemented at so far on the
The vector variables that you
dimensional objects.
single dimensional / one
-

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:

Example: of diss imilar lengths


creating 2 vectors

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)

Naming Columns and Rows: with matrices within the array by


We provide names to the rows, columns along
using the 'dimnames' parameter.

reatLIng 2 vectors having different lengtns.


vecl C(2, 4, 6)
vec2- c (11, 12, 13, 14, 1 16)
COlumn. names c ("COLA", '"OLB"', "COLC")
rOW.names C ("KONA", "koWi", "ROWC'")
matrix.names C "1Mal/ " , "1:ate")

resi < array (c (vectorl, vector2), dim c ,,),dimnames list

(column.names, row.names, matrix.nanes


print (res1 )

The output will be:


- --**------------- ******** ----------

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

Accessing and Indexing Array:


Indexing works similarly as it does with vectors, apart from that here you have to
state an index for more than
l-dimension.
W e have used square brackets for
denoting an index; here you have 4 choices to
specify the index (using positive & negative integers, via
clement names). logical values and using
Here are the lists of examples:

resl <- array (c (vecl,vec2), dim=c (3, 3, 2), dimnames


1ist (column . names, rOW. names,
matrix.names))
print (resl [3,,1])
t h i s statement prints the
3 rd row of the first matrix of
the àrray.
print (result [2,2,11)
t h e above
statement prints the element in the 2nd row and
2nd column of the 1st matrix.
print (result [,,2]J)
#the above
statement prir s the 2nd matrix
entirely

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)

# Elements are arranged sequentially by column.


N-matrix(c(3:14). nrow = 4, byrow = FALSE)

printN)

# Define the column and row names.


rownames = e("rowl", "row2", "row3", "row4")

colnames = c("coll", "co12", "col3")

Pmatrix(¢(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)

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

Accessing Elements of a Matrix


Elements of a matrix can be accessed by using the column and row index of the
element.
We consider the matrix P above to find the specific elements below.

# Define the column and row names.


rownanes c("rowl", "row2", "row3", "row4")
colnames = c("col| ", "col2". "col3")

# Create the matrix.


Pmatrix(c(3:14), nrow =4, byrow TRUE, dimnames list(rownames, colnames))

#Access the element at 3rd colunn and Ist row.


--- **********--

*********--~~-----.
**********-*******-*****-***--*~-------

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)

matrix2- matrix(c(5, 2, 0, 9, 3, 4), nrow =2)


print( matrix2)
Add the matrices.
result-matrix1 +matrix2
cat "Result of addition","n")
print(result)
# Subtract the matrices
result- matrixl - matrix2

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

Maurix Multiplication & Division


# Create two 2x3 matrices.
maurix I - matrix(c(3. 9, -1,4, 2, 6), nrow = 2)
prnt(matrix 1)

matrix2 matrix(c(5, 2, 0, 9, 3, 4), nrow =


2)
print(matrix2)
# Multiply the matrices.
result- matrix1 * matrix2

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 -

f [1] .1131.2]-1 1.32


2 9 4 6
I1].2] ,3]
1] 5 0 3
[2.1 2 94
Result of multiplication
][.2] 1.3]
1J 15 0 6
2.] 18 36 24
Result of division
. 2 ) 1.3
[1.] 0.6 -Inf 0.6666667
12, 4.5 0.4444444 1.5000000

You might also like