Trusted answers to developer questions

Onyejiaku Theophilus Chidalu

A **matrix** is simply a set of numbers arranged in rows and columns to form a rectangular array. The numbers inside a matrix are called the **elements**, or *entries*, of the matrix.

In this shot, we want to look at matrices in `R`

and access the elements present in a matrix. Before learning how to access the elements of a matrix, let’s see how a matrix can be created using the `matrix()`

function.

The ** matrix() function** in

`R`

is simply used to create a matrix.
The syntax of the `matrix()`

function is given as:```
matrix(data, nrow, ncol, byrow, dimnames)
```

The parameter values of the `matrix()`

function take the following parameters:

: This is a required value. It is the input vector which becomes the data elements of the matrix.`data`

: This is a required value. It is the desired number of rows.`nrow`

: This is a required value. It is the desired number of columns.`ncol`

: This is an optional value. It is logical. If`byrow`

`FALSE`

by default, the matrix is filled by columns. If otherwise, the matrix is filled by rows.: This is optional. It is an attribute for the matrix of length two (`dimnames`

`2`

), giving the respective names of rows and columns of the matrix.

# using the matrix() function to create a matrix mymatrix <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 2, byrow = FALSE, dimname = list(c("row1", "row2"), c("Col1", "Col2")) ) # print the matrix mymatrix

It is worth noting and remembering that the

`c()`

function is used to concatenate items together in`R`

.

To access the items or elements of a matrix, we use the ** []**. Inside this bracket must be two numbers separated by a comma. The first number is simply to specify the

```
[1, 2]
```

The expression above simply means that we are telling `R`

to return an element which can be found in the *first row* and in the *second column* of a matrix.

# creating a 2 by 2 matrix mymatrix <- matrix(c("apple", "banana", "cherry", "orange"), nrow = 2, ncol = 2) # printing the matrix mymatrix # to access row 1 column 2 element of the matrix mymatrix[1, 2]

RELATED TAGS

matrix

r

communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu

RELATED COURSES

View all Courses

Keep Exploring

Related Courses