In R programming, a matrix is a
two-dimensional data structure that contains elements of the same data type.
Matrices are useful for storing and manipulating data that can be represented
in rows and columns. In R, matrices can be created using the matrix() function.
Syntax:
matrix(data
= NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
Parameters:
l data:
The input vector that will be used to create the matrix.
l nrow:
The number of rows in the matrix.
l ncol:
The number of columns in the matrix.
l byrow:
A logical value indicating whether the matrix should be filled by rows or
columns.
l dimnames:
A list with names for the rows and columns.
Ø
Types of Matrices
There
are different types of matrices in R, which include:
l Numeric
matrix: A matrix that contains numeric values.
l Character
matrix: A matrix that contains character values.
l Logical
matrix: A matrix that contains logical values (TRUE or
FALSE).
l Integer
matrix: A matrix that contains integer values.
Ø
Accessing Elements of a Matrix:
In
R, matrix elements can be accessed using row and column indices. The index of
the first element in a matrix is [1, 1].
#
create a matrix
m
<- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
#
access matrix elements
m[1,
1] # returns 1
m[1,
2] # returns 3
m[2,
1] # returns 2
m[2,
2] # returns 4
Ø
Modifying Elements of a Matrix:
Matrix
elements can be modified using the assignment operator (<-).
#
modify matrix elements
m[1,
1] <- 10
m[2,
2] <- 20
#
print the modified matrix
m
Output:
[,1]
[,2]
[1,]
10
3
[2,]
2 20
Ø
Concatenating Matrices:
Matrices
can be concatenated by rows or columns using the cbind() and rbind() functions,
respectively.
#
create two matrices
m1
<- matrix(c(1, 2, 3, 4), nrow = 2)
m2
<- matrix(c(5, 6, 7, 8), nrow = 2)
#
concatenate matrices by columns
cbind(m1,
m2)
#
concatenate matrices by rows
rbind(m1,
m2)
Output:
#
concatenating matrices by columns
[,1]
[,2] [,3] [,4]
[1,]
1 3 5 7
[2,]
2 4 6 8
#
concatenating matrices by rows
[,1]
[,2]
[1,]
1 2
[2,]
3 4
[3,]
5 6
[4,]
7 8
No comments:
Post a Comment