You are on page 1of 26

R Operators

Operators are used to perform operations on values and variables. The R operators are
classified into six different categories:

Arithmetic operators
Comparison operators
Logical operators
Element-wise Logical operators
Membership operators
Assignment operators
Arithmetic Operators
Arithmetic operators are used to perform simple mathematical operations on numeric values
and vectors.
Operator Meaning Example
+ Addition x+y
– Subtraction x–y
* Multiplication x*y
/ Division x/y
%% Modulus x %% y
^ Exponents x^y
%/% Integer division x %/% y

All the basic arithmetic operators can be performed on pairs of vectors. Each operation is
performed in an element-by-element manner.
Comparison Operators
Comparison operators are used to compare two values or vectors.

Operator Meaning Example


== Equal to x == y
!= Not equal to x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators
Logical operators are used to join two or more conditions.

Element-wise Logical Operators


These operators are used to perform logical operations on vectors in an element-by-element
manner.
Membership Operator
Membership operator is used to check if a specific item is present in the vector or the list.

Assignment Operators
Assignment operators are used to assign new values to variables.

Miscellaneous Operators
These operators are used to for special purposes.

Operator Description Example


: Generates a number sequence from a to b 1:10
%*% Multiplies two matrices m1 %*% m2

Operator Precedence (Order of Operations)


In R, every operator is assigned precedence. Operator Precedence determines which
operations are performed before which other operations.
Operators of highest precedence are performed first.

Operator Description
highest precedence ({ Function calls and grouping expressions (respectively)
[ [[ Indexing
:: ::: Access variables in a namespace
$@ Component / slot extraction
^ Exponentiation (right to left)
–+ Unary minus and plus
: Sequence operator
%any% Special operators
*/ Multiply, divide
+– (Binary) add, subtract
< > <= >= == != Ordering and comparison
! Negation
& && And
| || Or
~ As in formulas
-> ->> Rightward assignment
= Assignment (right to left)
<- <<- Assignment (right to left)
lowest precedence ? Help (unary and binary)
R Vector
A vector is a collection of elements, all the same type (similar to an array in other
programming languages but more versatile).

When using R, you will frequently encounter the four basic vector types viz. logical,
character, integer and double (often called numeric).

Create a vector
In R, there are several ways to create a new vector; the simplest is to use the c() function.

# integer vector
c(1, 2, 3, 4, 5, 6)
[1] 1 2 3 4 5 6
# double vector
c(1*pi, 2*pi, 3*pi, 4*pi)
[1] 3.141593 6.283185 9.424778 12.566371
# character vector
c("red", "green", "blue")
[1] "red" "green" "blue"
# logical vector
c(TRUE, FALSE, TRUE, FALSE)
[1] TRUE FALSE TRUE FALSE

As a vector contains elements of the same type, if you try to combine different type of
elements, the c() function converts (coerces) them into a single type.

# numerics are converted to characters


v <- c(1, 2, 3, "a", "b", "c")
v
[1] "1" "2" "3" "a" "b" "c"
# logical are turned to numerics
v <- c(1, 2, 3, TRUE, FALSE)
v
[1] 1 2 3 1 0

You can check the type of a vector using typeof() function.

Create a Sequence
You can also create a vector using:

The : Operator
You can generate an equally spaced sequence of numbers, by using the : sequence
operator.

# sequence of numbers from 1 to 10


1:10
[1] 1 2 3 4 5 6 7 8 9 10
The seq() Function
The seq() function works the same as the : operator, except you can specify a different
increment (step size).

# sequence of numbers from 1 to 10 with increment of 2


seq(from=1,to=10,by=2)
[1] 1 3 5 7 9
The rep() Function
With rep() function you can generate a sequence by simply repeating certain values.

# repeat a value 6 times


rep(x=1,times=6)
[1] 1 1 1 1 1 1
# repeat a vector 3 times
rep(x=c(1,2,3),times=3)
[1] 1 2 3 1 2 3 1 2 3

Change the Vector Type


By using the as.vector() function, you can change the vector type.

# Turn numerical vector to character


v <- c(0, 1, 2, 3, 4, 5)
as.vector(v, mode="character")
[1] "0" "1" "2" "3" "4" "5"
# Turn numerical vector to logical
v <- c(0, 1, 2, TRUE, FALSE)
as.vector(v, mode="logical")
[1] FALSE TRUE TRUE TRUE FALSE

Naming a Vector
Each element of a vector can have a name. It allows you to access individual elements by
names. You can give a name to the vector element with the names() function.

v <- c("Apple", "Banana", "Cherry")


names(v) <- c("A", "B", "C")
v
A B C
"Apple" "Banana" "Cherry"
You can also give a name to the vector element while creating a vector.

v <- c("A"="Apple", "B"="Banana", "C"="Cherry")


v
A B C
"Apple" "Banana" "Cherry"

Subsetting Vectors
There are several ways to subset a vector (extract a value from the vector). You can do this
by combining square brackets [] with:

Positive integers
Negative integers
Logical values
Names

Subsetting with Positive Integers

Subsetting with positive integers returns the elements at the specified positions. Note that
vector positioning starts from 1.

v <- c("a","b","c","d","e","f")
# select 3rd element
v[3]
[1] "c"
# select 5th element
v[5]
[1] "e"

You can select multiple elements at once by using a vector of indexes.

v <- c("a","b","c","d","e","f")
# select elements from index 2 to 5
v[2:5]
[1] "b" "c" "d" "e"
# select elements from index 1 to 6 by increment 2
v[seq(from=1,to=6,by=2)]
[1] "a" "c" "e"

The indexing vector need not be a simple sequence. You can select elements anywhere
within the vector.

v <- c("a","b","c","d","e","f")
# select 1st, 3rd, 5th and 6th element
v[c(1,3,5,6)]
[1] "a" "c" "e" "f"

Subsetting by Negative Integer


Subsetting with negative integers will omit the elements at the specified positions.

v <- c("a","b","c","d","e","f")
# omit first element
v[-1]
[1] "b" "c" "d" "e" "f"
# omit elements from index 2 to 5
v[-2:-5]
[1] "a" "f"
# omit 1st, 3rd and 5th element
v[c(-1,-3,-5)]
[1] "b" "d" "f"

Subsetting by Logical Values


Subsetting with logical values will return the elements where the corresponding logical value
is TRUE.

v <- c(1,2,3,4,5,6)
v[c(TRUE,FALSE,TRUE,FALSE,TRUE,FALSE)]
[1] 1 3 5
You can also use a logical vector to select elements based on a condition.

# select even elements


v <- c(1,2,3,4,5,6,7,8,9)
v[v %% 2 == 0]
[1] 2 4 6 8
# skip values from 4 to 7
v <- c(1,2,3,4,5,6,7,8,9)
v[v < 4 | v > 7]
[1] 1 2 3 8 9
Subsetting by Names
Subsetting with names will return the elements having the matching names.

v <- c("A"="Apple", "B"="Banana", "C"="Cherry")


v
A B C
"Apple" "Banana" "Cherry"
# select element 'A'
v["A"]
A
"Apple"
# select element 'B'
v["B"]
B
"Banana"

Modify Vector Elements


Modifying a vector element is pretty straightforward. You use the [] to access the element,
and simply assign a new value.

v <- c("a","b","c","d","e","f")
v[3] <- 1
v
[1] "a" "b" "1" "d" "e" "f"
You can also modify more than one element at once.

v <- c("a","b","c","d","e","f")
v[1:3] <- c(1,2,3)
v
[1] "1" "2" "3" "d" "e" "f"
Add Elements to a Vector
The c() function can also be used to add elements to a vector.

v <- c(1,2,3)
# Add a single value to v
v <- c(v,4)
v
[1] 1 2 3 4
# Append an entire vector to v
w <- c(5,6,7,8)
v <- c(v,w)
v
[1] 1 2 3 4 5 6 7 8

Insert Element into a Vector


To insert an element into the middle of a vector, use append() function.

# Insert 99 after 5th element


append(1:10, 99, after=5)
[1] 1 2 3 4 5 99 6 7 8 9 10
# Insert 99 at the start
append(1:10, 99, after=0)
[1] 99 1 2 3 4 5 6 7 8 9 10
Combine Multiple Vectors
If the arguments to the c() function are vectors, it flattens them and combines them into one
single vector.

# Combine three vectors


v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
c(v1, v2, v3)
[1] 1 2 3 4 5 6 7 8 9
# Combine a vector and a sequence
v <- c(1, 2, 3)
c(v, 4:9)
[1] 1 2 3 4 5 6 7 8 9

Vector Arithmetic
Vector operations are one of R’s great strengths. All the basic arithmetic operators can be
performed on pairs of vectors. Each operation is performed in an element-by-element
manner.

v1 <- c(11,12,13,14,15)
v2 <- c(1,2,3,4,5)
# addition
v1 + v2
[1] 12 14 16 18 20
# subtraction
v1 - v2
[1] 10 10 10 10 10
# multiplication
v1 * v2
[1] 11 24 39 56 75
# division
v1 / v2
[1] 11.000000 6.000000 4.333333 3.500000 3.000000
# exponents
v1 ^ v2
[1] 11 144 2197 38416 759375

If one operand is a vector and the other is a scalar, then the operation is performed between
every vector element and the scalar.

# Arithmetic operations on a vector and a scalar


v <- c(1,2,3,4,5)
# addition
v+2
[1] 3 4 5 6 7
# subtraction
v-2
[1] -1 0 1 2 3
# multiplication
v*2
[1] 2 4 6 8 10
# division
v/2
[1] 0.5 1.0 1.5 2.0 2.5
# exponents
v^2
[1] 1 4 9 16 25
You can also apply a function on each element of a vector.

v <- c(1,2,3,4,5)
sqrt(v)
[1] 1.000000 1.414214 1.732051 2.000000 2.236068
log(v)
[1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379

The Recycling Rule


Arithmetic operations are performed in an element-by-element manner. That works well
when both vectors have the same length. But, when the vectors have unequal lengths, R’s
Recycling Rule kicks in.

If we apply arithmetic operations to two vectors of unequal length, then the elements of the
shorter vector are recycled to match the longest vector.

long <- c(1,2,3,4,5,6)


short <- c(1,2,3)
long + short
[1] 2 4 6 5 7 9
Here, the elements of long and short are added together starting from the first element of
both vectors. When R reaches the end of the short vector, it starts again at the first element
of short and continues until it reaches the last element of the long vector.

Sort a Vector
You can sort a vector using the sort() function. You can also specify the order in which you
want to sort a vector.

# Sort an integer vector


v <- c(2,7,3,6,1,5,9)
sort(v,decreasing=FALSE)
[1] 1 2 3 5 6 7 9
sort(v,decreasing=TRUE)
[1] 9 7 6 5 3 2 1
# Sort a character vector
v <- c("f","c","g","a","d","e","b")
sort(v,decreasing=FALSE)
[1] "a" "b" "c" "d" "e" "f" "g"
sort(v,decreasing=TRUE)
[1] "g" "f" "e" "d" "c" "b" "a"

Find a Vector Length


To find the total number of elements in a vector, use length() function.

v <- c(1,2,3,4,5)
length(v)
[1] 5
Calculate Basic Statistics
You can calculate basic statistics by using below simple R functions.

Statistic Function
mean mean(x)
median median(x)
standard deviation sd(x)
variance var(x)
correlation cor(x, y)
covariance cov(x, y)

These functions take a vector of numbers as an argument and return the calculated statistic.

v <- c(1,2,3,4,5,6)
# mean
mean(v)
[1] 3.5
# median
median(v)
[1] 3.5
# standard deviation
sd(v)
[1] 1.870829
# variance
var(v)
[1] 3.5
# correlation
cor(v, 2:7)
[1] 1
# covariance
cov(v, 2:7)
[1] 3.5
R List
Vectors and matrices are incredibly useful data structure in R, but they have one distinct
limitation: they can store only one type of data.

Lists, however, can store multiple types of values at once. A list can contain a numeric
matrix, a logical vector, a character string, a factor object and even another list.

Create a List
Creating a list is much like creating a vector; just pass a comma-separated sequence of
elements to the list() function.

# A list of integers
lst <- list(1, 2, 3)
# A list of characters
lst <- list("red", "green", "blue")
# A list of mixed datatypes
lst <- list(1, "abc", 1.23, TRUE)
The best way to understand the contents of a list is to use the structure function str(). It
provides a compact display of the internal structure of a list.

lst <- list(1, "abc", 1.23, TRUE)


str(lst)
List of 4
$ : num 1
$ : chr "abc"
$ : num 1.23
$ : logi TRUE

Nested List
A list can contain sublists, which in turn can contain sublists themselves, and so on. This is
known as nested list or recursive vectors.

lst <- list(1, "abc", list("a","b","c"), TRUE)


str(lst)
List of 4
$ : num 1
$ : chr "abc"
$ :List of 3
..$ : chr "a"
..$ : chr "b"
..$ : chr "c"
$ : logi TRUE

Subsetting List by Position


There are two ways to extract elements from a list:

Using [[]] gives you the element itself.


Using [] gives you a list with the selected elements.
Using []
You can use [] to extract either a single element or multiple elements from a list. However,
the result will always be a list.

lst <- list(1, "abc", 1.23, TRUE, 1:3)


# extract 2nd element
lst[2]
[[1]]
[1] "abc"
# extract 5th element
lst[5]
[[1]]
[1] 1 2 3
# select 1st, 3rd and 5th element
lst[c(1,3,5)]
[[1]]
[1] 1
[[2]]
[1] 1.23
[[3]]
[1] 1 2 3
# exclude 1st, 3rd and 5th element
lst[c(-1,-3,-5)]
[[1]]
[1] "abc"
[[2]]
[1] TRUE
Using [[]]

You can use [[]] to extract only a single element from a list. Unlike [], [[]] gives you the
element itself.

lst <- list(1, "abc", 1.23, TRUE, 1:3)


# extract 2nd element
lst[[2]]
[1] "abc"
# extract 5th element
lst[[5]]
[1] 1 2 3

You can’t use logical vectors or negative numbers as indices when using [[]]

Difference Between Single Bracket [] and Double Bracket [[]]


The difference between [] and [[]] is really important for lists, because [[]] returns the element
itself while [] returns a list with the selected elements.

The difference becomes clear when we inspect the structure of the output – one is a
character and the other one is a list.

lst <- list("a","b","c","d","e","f")


class(lst[[1]])
[1] "character"
class(lst[1])
[1] "list"

The difference becomes annoyingly obvious when we cat the value. As you know cat() can
print any value except the structured object.

cat(lst[[1]], "\n")
a
cat(lst[1], "\n")
Error in cat(lst[1], "\n") :
argument 1 (type 'list') cannot be handled by 'cat'

Subsetting List by Names


Each list element can have a name. You can access individual element by specifying its
name in double square brackets [[]] or use $ operator.

months <- list(JAN=1, FEB=2, MAR=3, APR=4)


# extract element by its name
months[["MAR"]]
[1] 3
# same as above but using the $ operator
months$MAR
[1] 3
# extract multiple elements
months[c("JAN","APR")]
$JAN
[1] 1
$APR
[1] 4
$ works similarly to [[]] except that you don’t need to use quotes.

Subsetting Nested List


You can access individual items in a nested list by using the combination of [[]] or $ operator
and the [] operator.

lst <- list(item1 = 3.14,


item2 = list(item2a = 5:10,
item2b = c("a","b","c")))
# preserve the output as a list
lst[[2]][1]
$item2a
[1] 5 6 7 8 9 10
# same as above but simplify the output
lst[[2]][[1]]
[1] 5 6 7 8 9 10
# same as above with names
lst[["item2"]][["item2a"]]
[1] 5 6 7 8 9 10
# same as above with $ operator
lst$item2$item2a
[1] 5 6 7 8 9 10
# extract individual element
lst[[2]][[2]][3]
[1] "c"

Modify List Elements


Modifying a list element is pretty straightforward. You use either the [[]] or the $ to access
that element, and simply assign a new value.

# Modify 3rd list element


lst <- list("a","b","c","d","e","f")
lst[[3]] <- 1
str(lst)
List of 6
$ : chr "a"
$ : chr "b"
$ : num 1
$ : chr "d"
$ : chr "e"
$ : chr "f"

You can modify components using [] as well, but you have to assign a list of components.

# Modify 3rd list element using []


lst <- list("a","b","c","d","e","f")
lst[3] <- list(1)
str(lst)
List of 6
$ : chr "a"
$ : chr "b"
$ : num 1
$ : chr "d"
$ : chr "e"
$ : chr "f"
Using [] allows you to modify more than one component at once.

# Modify first three list elements


lst <- list("a","b","c","d","e","f")
lst[1:3] <- list(1,2,3)
str(lst)
List of 6
$ : num 1
$ : num 2
$ : num 3
$ : chr "d"
$ : chr "e"
$ : chr "f"

Add Elements to a List


You can use same method for modifying elements and adding new one. If the element is
already present in the list, it is updated else, a new element is added to the list.

lst <- list(1, 2, 3)


lst[[4]] <- 4
str(lst)
List of 4
$ : num 1
$ : num 2
$ : num 3
$ : num 4

By using append() method you can append one or more elements to the list.

lst <- list(1, 2, 3)


lst <- append(lst,c("a","b","c"))
str(lst)
List of 6
$ : num 1
$ : num 2
$ : num 3
$ : chr "a"
$ : chr "b"
$ : chr "c"

Remove an Element from a List


To remove a list element, select it by position or by name, and then assign NULL to it.

lst <- list("a","b","c","d","e")


lst[[3]] <- NULL
str(lst)
List of 4
$ : chr "a"
$ : chr "b"
$ : chr "d"
$ : chr "e"
Using [], you can delete more than one component at once.

# Remove first four element from a list


lst <- list("a","b","c","d","e")
lst[1:4] <- NULL
str(lst)
List of 1
$ : chr "e"

By using a logical vector, you can remove list elements based on the condition.

# Remove all negative list elements


lst <- list(-4,-3,-2,-1,0,1,2,3,4)
lst[lst <= 0] <- NULL
str(lst)
List of 4
$ : num 1
$ : num 2
$ : num 3
$ : num 4

Combine Lists
The c() does a lot more than just creating vectors. It can be used to combine lists into a new
list as well.

lst1 <- list("a","b","c")


lst2 <- list(1,2,3)
lst <- c(lst1, lst2)
str(lst)
List of 6
$ : chr "a"
$ : chr "b"
$ : chr "c"
$ : num 1
$ : num 2
$ : num 3
Flatten a List into a Vector
Basic statistical functions work on vectors but not on lists.

For example, you cannot directly compute the mean of list of numbers. In that case, you have to
flatten the list into a vector using unlist() first and then compute the mean of the result.

# Flatten the list into a vector and compute mean


lst <- list(5, 10, 15, 20, 25)
mean(unlist(lst))
[1] 15
Find List Length
To find the length of a list, use length() function.

lst <- list(5, 10, 15, 20)


length(lst)
[1] 4
R Matrix
A matrix is a collection of elements, all the same type, arranged in a two-dimensional layout.

In a nutshell, a matrix is just a vector that has two dimensions.

When using R, you will frequently encounter the four basic matrix types viz. logical,
character, integer and double (often called numeric).

Create a Matrix
You can create a matrix using the matrix() function and specifying the data and the number
of rows and columns to make the matrix.

# Create a numeric matrix


m <- matrix(1:6, nrow=2, ncol=3)
m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Matrix can contain character values as well.

# Create a character matrix


letters <- c("a","b","c","d","e","f")
m <- matrix(letters, nrow=2, ncol=3)
m
[,1] [,2] [,3]
[1,] "a" "c" "e"
[2,] "b" "d" "f"

You don’t have to specify both ncol and nrow. If you specify one, R will know automatically
what the other needs to be.

m <- matrix(1:6, nrow=2)


m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
By default, the matrix is filled column-by-column. By setting byrow=TRUE you can fill the
matrix row-by-row.

m <- matrix(1:6, nrow=2, ncol=3, byrow=TRUE)


m
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6

Combine Vectors into a Matrix


You can also create a matrix using the cbind() and rbind() functions. However, keep in mind
that the vectors that are being binded must be of equal length and same type.

v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
rbind(v1, v2, v3)
[,1] [,2] [,3]
v1 1 2 3
v2 4 5 6
v3 7 8 9

The cbind() function does something similar. It binds the vectors as columns of a matrix.

v1 <- c(1, 2, 3)
v2 <- c(4, 5, 6)
v3 <- c(7, 8, 9)
cbind(v1, v2, v3)
v1 v2 v3
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

Change Matrix Dimension


By using the dim() function you can get the dimension of the matrix without looking at the
structure.

# Print the dimension of a matrix


m <- matrix(1:6, nrow=2, ncol=3)
dim(m)
[1] 2 3
The dim() function can also be used to set the dimension of the matrix.

# Change the dimension of a matrix


# define a 2x3 matrix
m <- matrix(1:6, nrow=2, ncol=3)
m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

# make it 3x2
dim(m) <- c(3,2)
m
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

# make it 1x6
dim(m) <- c(1,6)
m
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6

Naming Matrix Rows and Columns


R lets you assign descriptive names to the rows and columns of a matrix. It is useful for
subsetting and printing the matrix.

You can do this by assigning two element list containing row and column names to the
dimnames attribute.

# Assign names to the rows and columns


m <- matrix(1:6, nrow=2, ncol=3)
dimnames(m) <- list(c("r1","r2"), c("c1","c2","c3"))
m
c1 c2 c3
r1 1 3 5
r2 2 4 6

You can even name the rows and columns while creating a matrix by passing dimnames
argument.

# Naming rows and columns while matrix creation


m <- matrix(1:6, nrow=2, ncol=3, dimnames=list(c("r1","r2"), c("c1","c2","c3")))
m
c1 c2 c3
r1 1 3 5
r2 2 4 6

By using the rownames() and colnames() function you can assign row names and column
names separately.

# Assign names to the rows and columns separately


m <- matrix(1:6, nrow=2, ncol=3)
rownames(m) <- c("r1","r2")
colnames(m) <- c("c1","c2","c3")
m
c1 c2 c3
r1 1 3 5
r2 2 4 6

You can use the same dimnames(), colnames() and rownames() functions to print column
names and row names.

# print column names


colnames(m)
[1] "c1" "c2" "c3"
# print row names
rownames(m)
[1] "r1" "r2"
# print both
dimnames(m)
[[1]]
[1] "r1" "r2"
[[2]]
[1] "c1" "c2" "c3"

Subsetting Matrices
In R, subsetting elements from matrices is much like subsetting elements from vectors.

The only difference is that you now have to specify both the row and the column position, in
the order of [row, column].

Subsetting by Positive Integer


Subsetting with positive integers returns the elements at the specified positions.

m <- matrix(1:9, nrow=3, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
# subset for 2nd row
m[2,]
[1] 2 5 8
# subset for 3rd column
m[,3]
[1] 7 8 9
# select single element
m[2,3]
[1] 8
# subset for row 1 and 2 but keep all columns
m[1:2,]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
# subset for both rows and columns
m[1:2,2:3]
[,1] [,2]
[1,] 4 7
[2,] 5 8
# use a vector to subset
m[1:2,c(1, 3)]
[,1] [,2]
[1,] 1 7
[2,] 2 8

When you subset for a single row or a column, the result will always be a vector. To avoid
this you can set the drop argument to FALSE.

m <- matrix(1:9, nrow=3, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
# simplifies the output to a vector
m[, 2]
[1] 4 5 6
class(m[, 2])
[1] "integer"
# preserves output as a matrix
m[, 2, drop = FALSE]
[,1]
[1,] 4
[2,] 5
[3,] 6
class(m[, 2, drop = FALSE])
[1] "matrix"

Subsetting by Negative Integer


Subsetting with negative integers will omit the elements at the specified positions.

m <- matrix(1:9, nrow=3, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
# omit 2nd row
m[-2,]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 3 6 9
# omit 3rd column
m[,-3]
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
# omit 2nd row and 3rd column
m[-2,-3]
[,1] [,2]
[1,] 1 4
[2,] 3 6

Subsetting by Logical Values


Subsetting with logical values will return the elements where the corresponding logical value
is TRUE.

m <- matrix(1:9, nrow=3, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
# select elements where corresponding logical value is TRUE
m[c(TRUE,FALSE,TRUE),c(TRUE,TRUE,FALSE)]
[,1] [,2]
[1,] 1 4
[2,] 3 6
# select elements greater than 5
m[m > 5]
[1] 6 7 8 9
# select even elements
m[m %% 2 == 0]
[1] 2 4 6 8

Subsetting by Names
Subsetting with names will return the elements having the matching names.

m <- matrix(1:9, nrow=3, ncol=3)


dimnames(m) <- list(c("r1","r2","r3"), c("c1","c2","c3"))
# subset for 2nd row
m["r2",]
c1 c2 c3
2 5 8
# subset for 3rd column
m[,"c3"]
r1 r2 r3
7 8 9
# subset for 1st and 3rd row but keep all columns
m[c("r1","r3"),]
c1 c2 c3
r1 1 4 7
r3 3 6 9
# select single element
m["r2","c3"]
[1] 8

Add New Rows and Columns to Matrix


You can use the cbind() and rbind() functions for adding new rows and columns to the matrix
as well. However, keep in mind that the vectors that are being added must be of equal length
and same type.

m <- matrix(1:6, nrow=2, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
# add new column
cbind(m, c(7,8))
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
# add new row
rbind(m, c(10,20,30))
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[3,] 10 20 30
Modify Matrix Elements
Modifying a matrix element is pretty straightforward. Access the element using [] operator
and simply assign a new value.

m <- matrix(1:6, nrow=2, ncol=3)


# moidfy single element
m[1,2] <- 99
m
[,1] [,2] [,3]
[1,] 1 99 5
[2,] 2 4 6
# modify 2nd row
m[2,] <- c(10,20,30)
m
[,1] [,2] [,3]
[1,] 1 99 5
[2,] 10 20 30
# modify elements less than 5
m[m > 5] <- 0
m
[,1] [,2] [,3]
[1,] 1 0 5
[2,] 0 0 0

Matrix Operations
The most powerful feature of R is the ease of dealing with matrix operations. Because much
of statistics depend on matrix operations, R perform them in an easy and optimized way:

Matrix transpose
Creating an identity matrix
Scalar multiple of a matrix
Matrix addition and subtraction
Matrix multiplication
Matrix inversion

Matrix Transpose
The transpose of a matrix is simply a flipped version of the original matrix obtained by
switching rows with columns. To transpose a matrix, use t() function.

m <- matrix(1:6, nrow=2, ncol=3)


m
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
t(m)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6

Creating an Identity Matrix


You can create an identity matrix using the diag() function. Its behavior depends on what
argument you pass.
If you pass a single positive integer, then diag() will create an identity matrix of that
dimension.

# Create a 3x3 identity matrix


diag(3)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
If you pass a matrix, diag() will return the diagonal elements of the matrix.

# Return diagonal elements of the matrix


m <- matrix(1:9, nrow=3, ncol=3)
m
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
diag(m)
[1] 1 5 9

Scalar Multiple of a Matrix


When you multiply a matrix by a scalar value (a single number), every individual element is
multiplied by that value.

# Multiply each matrix element by 10


m <- matrix(1:6, nrow=2, ncol=3)
m * 10
[,1] [,2] [,3]
[1,] 10 30 50
[2,] 20 40 60

Matrix Addition and Subtraction


R performs addition or subtraction of two matrices of equal size in an element-wise manner.
Meaning, corresponding elements are added or subtracted from one another, depending on
the operation.

m1 <- matrix(1:6, nrow=2, ncol=3)


m1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
m2 <- matrix(-6:-1, nrow=2, ncol=3)
m2
[,1] [,2] [,3]
[1,] -6 -4 -2
[2,] -5 -3 -1
# addition
m1 + m2
[,1] [,2] [,3]
[1,] -5 -1 3
[2,] -3 1 5
# subtraction
m1 - m2
[,1] [,2] [,3]
[1,] 7 7 7
[2,] 7 7 7

Matrix Multiplication
Unlike scalar multiplication, matrix multiplication is not a simple element-by-element
calculation, and the standard * operator cannot be used. Instead, you must use R’s matrix
product operator %*%.

m1 <- matrix(1:6, nrow=2, ncol=3)


m1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
m2 <- matrix(1:6, nrow=3, ncol=2)
m2
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
# multiplication
m1 %*% m2
[,1] [,2]
[1,] 22 49
[2,] 28 64

Matrix Inversion
The inverse of a matrix can be calculated by using the solve() function.

m <- matrix(1:4, nrow=2, ncol=2)


m
[,1] [,2]
[1,] 1 3
[2,] 2 4
solve(m)
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5

Matrix Length
You can find the total number of values in a matrix using the length() function.

m <- matrix(1:6, nrow=2, ncol=3)


length(m)
[1] 6

You might also like