Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

matrix
r
communitycreator

How to access the elements of a matrix in R

Onyejiaku Theophilus Chidalu

Overview

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.

Creating a matrix

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:

  • data: This is a required value. It is the input vector which becomes the data elements of the matrix.
  • nrow: This is a required value. It is the desired number of rows.
  • ncol: This is a required value. It is the desired number of columns.
  • byrow: This is an optional value. It is logical. If FALSE by default, the matrix is filled by columns. If otherwise, the matrix is filled by rows.
  • dimnames: This is optional. It is an attribute for the matrix of length two (2), giving the respective names of rows and columns of the matrix.

Example

# 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.

Accessing the elements of a matrix

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 row where the element you seek can be found, while the second number is used to specify the column where the element you seek can be found. For example:

[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