R Matrices and Arrays


A matrix is a two dimensional data set with columns and rows.

A column is a vertical representation of data, while a row is a horizontal representation of data.

A matrix can be created with the matrix() function. Specify the nrow and ncol parameters to get the amount of rows and columns:

Example:
# Create a matrix
A <- matrix(c(1,2,3,4,5,6), nrow = 3, ncol = 2)

# Print the matrix
print(A)

Output:
[,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

You can also create a matrix with strings:

Example
# Create a matrix
A <- matrix(c("apple","grape","banana","orange"), nrow = 2, ncol = 2)

# Print the matrix
A

Output:
[,1]    [,2]    
[1,] "apple" "banana"
[2,] "grape" "orange"

Access Matrix Items

You can access the items by using [ ] brackets. The first number "1" in the bracket specifies the row-position, while the second number "2" specifies the column-position:

The whole row can be accessed if you specify a comma after the number in the bracket:

The whole column can be accessed if you specify a comma before the number in the bracket:

Example:
# Create a matrix
A <- matrix(c("apple","grape","banana","orange"), nrow = 2, ncol = 2)

# Print the matrix
A
#Print 1 row 2 column element
A[1,2]
#Print second row
A[2,]
#Print second column
A[,2]
Output:
[,1]    [,2]    
[1,] "apple" "banana"
[2,] "grape" "orange"
[1] "banana"
[1] "grape"  "orange"
[1] "banana" "orange"

Access More Than One Row

More than one row can be accessed if you use the c() function:
# Create a matrix
A <- matrix(c("apple","grape","banana","orange","plum","cherry","pineapple","melon","pear"), nrow = 3, ncol = 3)

# Print the matrix
A
#printing row 1 and 2 can also use A[1:2,]
A[c(1,2),]

Output:
[,1]     [,2]     [,3]       
[1,] "apple"  "orange""pineapple"
[2,] "grape"  "plum"   "melon"    
[3,] "banana" "cherry" "pear"     
     [,1]    [,2]     [,3]       
[1,] "apple" "orange" "pineapple"
[2,] "grape" "plum"   "melon"    


Access More Than One Column

More than one column can be accessed if you use the c() function:

# Create a matrix
A <- matrix(c("apple","grape","banana","orange","plum","cherry","pineapple","melon","pear"), nrow = 3, ncol = 3)

# Print the matrix
A
#Printing column 1 and 2 can also use A[,1:2]
A[,c(1,2)]

Output:
[,1]     [,2]     [,3]       
[1,] "apple"  "orange" "pineapple"
[2,] "grape"  "plum"   "melon"    
[3,] "banana" "cherry" "pear"     
     [,1]     [,2]    
[1,] "apple"  "orange"
[2,] "grape"  "plum"  
[3,] "banana" "cherry"


Add Rows and Columns

Use the cbind() function to add additional columns in a Matrix:

# Create a matrix
A <- matrix(c("apple","grape","banana","orange","plum","cherry","pineapple","melon","pear"), nrow = 3, ncol = 3)

# Print the matrix
A
#Add a new column
A=cbind(A,c("strawberry", "blueberry", "raspberry"))
#Print the matrix
A
Output:
[,1]     [,2]     [,3]       
[1,] "apple"  "orange" "pineapple"
[2,] "grape"  "plum"   "melon"    
[3,] "banana" "cherry" "pear"     
     [,1]     [,2]     [,3]        [,4]        
[1,] "apple"  "orange" "pineapple" "strawberry"
[2,] "grape"  "plum"   "melon"     "blueberry" 
[3,] "banana" "cherry" "pear"      "raspberry" 

Note: The cells in the new column must be of the same length as the existing matrix.

Use the rbind() function to add additional rows in a Matrix:
# Create a matrix
A <- matrix(c("apple","grape","banana","orange","plum","cherry","pineapple","melon","pear"), nrow = 3, ncol = 3)

# Print the matrix
A
#Add a new row
A=rbind(A,c("strawberry", "blueberry", "raspberry"))
A

Remove Rows and Columns

Use the c() function to remove rows and columns in a Matrix:
Example removing 1 row and 1 column
# Create a matrix
A <- matrix(c("apple","grape","banana","orange","plum","cherry","pineapple","melon","pear"), nrow = 3, ncol = 3)

# Print the matrix
A
#removing 1 row and 1 column
A=A[-c(1),-c(1)]
# Print the matrix
A
Output:
[,1]     [,2]     [,3]       
[1,] "apple"  "orange" "pineapple"
[2,] "grape"  "plum"   "melon"    
[3,] "banana" "cherry" "pear"     
     [,1]     [,2]   
[1,] "plum"   "melon"
[2,] "cherry" "pear" 

Check if an Item Exists

To find out if a specified item is present in a matrix, use the %in% operator:

Example
A <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)

"apple" %in% A

Output:
[1] TRUE


Number of Rows and Columns


Use the dim() function to find the number of rows and columns in a Matrix:
Example:
A <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
dim(A)
Output:
[1] 2 2

Matrix Length

Use the length() function to find the dimension of a Matrix:

A <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
length(A)
Output:
[1] 4

Total cells in the matrix is the number of rows multiplied by number of columns.
In the example above: Dimension = 2*2 = 4.

Loop Through a Matrix

You can loop through a Matrix using a for loop. The loop will start at the first row, moving right:

Example

Loop through the matrix items and print them:
A <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2)
for (rows in 1:nrow(A)) {
  for (columns in 1:ncol(A)) {
    cat(A[rows, columns]," ")
  }
  cat("\n")
}
Output:
apple  cherry  
banana  orange  

Combine two Matrices

Again, you can use the rbind() or cbind() function to combine two or more matrices together:

Example:
A <- matrix(c("apple", "banana", "cherry", "grape"), nrow = 2, ncol = 2)
B <- matrix(c("orange", "mango", "pineapple", "watermelon"), nrow = 2, ncol = 2)
A
B
# Adding it as a rows
AB_Combined <- rbind(A, B)
AB_Combined

# Adding it as a columns
AB_Combined <- cbind(A, B)
AB_Combined
Output:
[,1]     [,2]    
[1,] "apple"  "cherry"
[2,] "banana" "grape" 
[,1]     [,2]        
[1,] "orange" "pineapple" 
[2,] "mango"  "watermelon"
     [,1]     [,2]        
[1,] "apple"  "cherry"    
[2,] "banana" "grape"     
[3,] "orange" "pineapple" 
[4,] "mango"  "watermelon"
     [,1]     [,2]     [,3]     [,4]        
[1,] "apple"  "cherry" "orange" "pineapple" 
[2,] "banana" "grape"  "mango"  "watermelon"

Creating special matrices

R allows creation of various different types of matrices with the use of arguments passed to the matrix() function.
Matrix where all rows and columns are filled by a single constant ‘k’:
To create such a matrix the syntax is given below:

Syntax: matrix(k, m, n)
Parameters:
k: the constant
m: no of rows
n: no of columns

# R program to illustrate
# special matrices
Example:
# Matrix having 3 rows and 3 columns
# filled by a single constant 5
print(matrix(5, 3, 3))
Output:
[,1] [,2] [,3]
[1,]    5    5    5
[2,]    5    5    5
[3,]    5    5    5

Diagonal matrix:
A diagonal matrix is a matrix in which the entries outside the main diagonal are all zero. To create such a matrix the syntax is given below:

Syntax: diag(k, m, n)
Parameters:
k: the constants/array
m: no of rows
n: no of columns
Example:
# R program to illustrate
# special matrices

# Diagonal matrix having 3 rows and 3 columns
# filled by array of elements (5, 3, 3)
print(diag(c(5, 3, 3), 3, 3))
Output:
[,1] [,2] [,3]
[1,]    5    0    0
[2,]    0    3    0
[3,]    0    0    3

Identity matrix:
A square matrix in which all the elements of the principal diagonal are ones and all other elements are zeros. To create such a matrix the syntax is given below:

Syntax: diag(k, m, n)
Parameters:
k: 1
m: no of rows
n: no of columns
Example:
# R program to illustrate
# special matrices

# Identity matrix having
# 3 rows and 3 columns
print(diag(1, 3, 3))
Output:
[,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

once a matrix is created then
  • How can you know the dimension of the matrix?
  • How can you know how many rows are there in the matrix?
  • How many columns are in the matrix?
  • How many elements are there in the matrix? are the questions we generally wanted to answer.
Example:
# R program to illustrate
# matrix metrics

# Create a 3x3 matrix
A = matrix(
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
cat("The 3x3 matrix:\n")
print(A)

cat("Dimension of the matrix:\n")
print(dim(A))

cat("Number of rows:\n")
print(nrow(A))

cat("Number of columns:\n")
print(ncol(A))

cat("Number of elements:\n")
print(length(A))
# OR
print(prod(dim(A)))


Output:
The 3x3 matrix:
[,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Dimension of the matrix:
[1] 3 3
Number of rows:
[1] 3
Number of columns:
[1] 3
Number of elements:
[1] 9
[1] 9

Element wise Matrix Operations
# R program to do matrix operations

# Creating 1st Matrix
A = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)

# Creating 2nd Matrix
B = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3)

# Getting number of rows and columns
num_of_rows = nrow(B)
num_of_cols = ncol(B)

# Creating matrix to store results
#sum = matrix(, nrow = num_of_rows, ncol = num_of_cols)

# Printing Original matrices
print(A)
print(B)
sum=A+B
diff=A-B
prod=A*B
div=A/B
print(sum)
print(diff)
print(prod)
print(div)

Multiplication using %*% operator

The Operator%*% is used for matrix multiplication satisfying the condition that the number of columns in the first matrix is equal to the number of rows in second. If matrix A[M, N] and matrix B[N, Z] are multiplied then the resultant matrix will be of dimension M*Z.
Example:
# R program for matrix multiplication
# Creating matrices
A <- matrix(1:6, nrow=2)
B <- matrix(1:3, nrow=3)
A
B
# Multiplying matrices using operator
print(A %*% B)
Output:
[,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
     [,1]
[1,]    1
[2,]    2
[3,]    3
[,1]
[1,]   22
[2,]   28

Determinant of a matrix
# Create 2 different vectors.
a1 <- c(1, 2)
a2 <- c(3, 6)
# Bind the 2 matrices row-wise
# using the rbind() function.
A <- rbind(a1, a2)
A
#determinant of matrix
print("determinant")
print(det(A))
Output:
[,1] [,2]
a1    1    2
a2    3    6
[1] "determinant"
[1] 0

# Create 3 different vectors.
a1 <- c(3, 2, 8)
a2 <- c(6, 3, 2)
a3 <- c(5, 2, 4)

# Bind the 3 matrices row-wise
# using the rbind() function.
A <- rbind(a1, a2, a3)

# determinant of matrix
print(det(A))

Output:
-28

Note:inv() function can be used to find the inverse of a matrix.Ensure that you have installed the ‘matlib’ package in your environment.


Arrays

Compared to matrices, arrays can have more than two dimensions.

We can use the array() function to create an array, and the dim parameter to specify the dimensions:
Example:
# An array with one dimension with values ranging from 1 to 24
thisarray <- c(1:10)
thisarray

# An array with more than one dimension
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray
Output:
[1]  1  2  3  4  5  6  7  8  9 10
, , 1

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7    1
[4,]    4    8    2

, , 2

     [,1] [,2] [,3]
[1,]    3    7    1
[2,]    4    8    2
[3,]    5    9    3
[4,]    6   10    4

Note: Arrays can only have one data type.

Access Array Items

You can access the array elements by referring to the index position. You can use the [] brackets to access the desired elements from an array:

The syntax is as follow: array[row position, column position, matrix level]

You can also access the whole row or column from a matrix in an array, by using the c() function:

Example:
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray
multiarray[2, 3, 2]

Output:
    [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12, , 2

     [,1] [,2] [,3]
[1,]   13   17   21
[2,]   14   18   22
[3,]   15   19   23
[4,]   16   20   24

[1] 22

Example:
thisarray <- c(1:24)

# Access all the items from the first row from matrix one
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray
multiarray[c(1),,1]

# Access all the items from the first column from matrix one
multiarray[,c(1),1]

Output:
   [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    48   12

, , 2

     [,1] [,2] [,3]
[1,]   13   17   21
[2,]   14   18   22
[3,]   15   19   23
[4,]   16   20   24

[1] 1 5 9
[1] 1 2 3 4

Array Length and Dimension

Use the length() function and dim () to find the length and dimension of an array:

Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

length(multiarray)
dim(multiarray)

Output:
[1] 24
[1] 4 3 2

Naming of  Rows and Columns of multidimensional arrays

The row names, column names and matrices names are specified as a vector of the number of rows, number of columns and number of matrices respectively. By default, the rows, columns and matrices are named by their index values.

row_names <- c("row1", "row2")
col_names <- c("col1", "col2", "col3")
mat_names <- c("Mat1", "Mat2")

# the naming of the various elements
# is specified in a list and
# fed to the function
arr = array(2:14, dim = c(2, 3, 2),dimnames = list(row_names,col_names, mat_names))
print (arr)

Output:
, , Mat1

    col1 col2 col3
row1    2    4    6
row2    3    5    7

, , Mat2

     col1 col2 col3
row1    8   10   12
row2    9   11   13

Loop Through an Array

You can loop through the array items by using a for loop:

Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

for(x in multiarray){
print(x)
}


Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types