**Matrix is an important data structure in R** – Matrices are **vectors with a dimension attribute or extension of Vecotrs.** The dimension attribute is itself an integer vector of length 2 (number of rows, number of columns).

**m <- 1:10**

**dim(m) <- c(2, 5)**

**m**

Output:-

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

[1,] 1 3 5 7 9

[2,] 2 4 6 8 10

**As per Datacamp (Introduction to R online course):-**

In R, a matrix is a collection of elements of the same data type (numeric, character, or logical) arranged into a fixed number of rows and columns. Since you are only working with rows and columns, a matrix is called two-dimensional.

You can construct a matrix in R with the matrix() function. Consider the following example:

**matrix(1:9, byrow = TRUE, nrow = 3)**

Output:-

[,1] [,2] [,3]

[1,] 1 2 3

[2,] 4 5 6

[3,] 7 8 9

Note:- Argument byrow= True indicates that the matrix is filled by the rows, for filling by column we can use brow=False which is given by default.

Important Point:-

matrix() will create matrix on basis of Value of nrow or ncol – no need to give both values at once.

matrix(1:12, nrow = 3)
Output:- |
matrix(1:12, ncol=3)
output:- |

**Second way to create a Matrix:-**

Matrices can also be created **directly from vectors** by adding a dimension attribute.

m <- 1:10

> m

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

> dim(m) <- c(2, 5)

> m

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

[1,] 1 3 5 7 9

[2,] 2 4 6 8 10

**Third Way to create a Matrix **

with the cbind() and rbind() functions.

> x <- 1:4

> yy<-10:14

**cbind(x,y)**

*Error in cbind(x, y) : object ‘y’ not found*

> cbind(x,yy)

x yy

[1,] 1 10

[2,] 2 11

[3,] 3 12

[4,] 4 13

[5,] 1 14

*Warning message:*

*In cbind(x, yy) :*

* number of rows of result is not a multiple of vector length (arg 1)*

> x<- 1:4

> yy<- 10:13

> cbind(x,yy)

x yy

[1,] 1 10

[2,] 2 11

[3,] 3 12

[4,] 4 13

** rbind(x,yy)**

[,1] [,2] [,3] [,4]

x 1 2 3 4

yy 10 11 12 13

Matrix Vs Data Frames Via

is.matrix(as.matrix(1:10))
!is.matrix(warpbreaks) # data.frame, NOT matrix!
warpbreaks[1:10,] is.matrix(warpbreaks[1:10,]) as.matrix(warpbreaks[1:10,]) # using as.matrix.data.frame(.) method ## Example of setting row and column namesmdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE, |
is.matrix(as.matrix(1:10)) [1] TRUE> !is.matrix(warpbreaks) # data.frame, NOT matrix! [1] TRUE> warpbreaks[1:10,] breaks wool tension 1 26 A L 2 30 A L 3 54 A L 4 25 A L 5 70 A L 6 52 A L 7 51 A L 8 26 A L 9 67 A L 10 18 A M> is.matrix(warpbreaks[1:10,]) [1] FALSE
> as.matrix(warpbreaks[1:10,]) # using as.matrix.data.frame(.) method breaks wool tension
> mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE, |