What is the is.matrix() function in R?

Overview

The is.matrix() function in R will return a logical value (TRUE or FALSE), indicating whether or not an argument passed to it is a vector with a dim attribute of length 2.

Syntax

is.matrix(x)
Syntax for the is.matrix() function

Parameter value

The is.matrix() function takes a single parameter value, x, representing any R object.

Return value

The is.matrix() function returns TRUE if the argument is a vector and has an attribute dim of length 2. Otherwise, it returns FALSE.

Example

# creating R objects
mymatrix <- matrix(c("apple", "banana", "cherry", "grape", "melon", "pineapple"), nrow = 3, ncol = 3)
myvector <- c("apple", "banana", "cherry", "grape", "melon", "pineapple")
# checking if the objects is/are a matrix
is.matrix(mymatrix)
is.matrix(myvector)
# obtaining their dim attribute
dim(mymatrix)
dim(myvector)

Explanation

  • Line 2: We create an R object, mymatrix, using the matrix() function.
  • Line 3: We create another R object, myvector.
  • Line 6: We implement the is.matrix() function on the object, mymatrix to see if it's a matrix or not.
  • Line 7: We implement the is.matrix() function on the object, myvector to see if it's a matrix or not.
  • Line 10–11: We check the dim attribute of both objects.
Note: The attribute dim for the object, myvector, is not of length 2, unlike the other matrix object with a length of 2. To make myvector into a matrix object, we only need to pass the dim attribute.

Example

# creating R objects
mymatrix <- matrix(c("apple", "banana", "cherry", "grape", "melon", "pineapple"), nrow = 3, ncol = 3)
myvector <- c("apple", "banana", "cherry", "grape", "melon", "pineapple")
# passing an attribute to the vector object
dim(myvector) <- c(2,3)
# Now check to see if it is a matrix object or not
is.matrix(myvector)

Code explanation

  • Line 2: We create an R object, mymatrix, using the matrix() function.
  • Line 3: We create another R object, myvector.
  • Line 6: We use the dim attribute, we passed a dimension of 2 by 3 to the object to make it a matrix with dim attribute of length 2.
  • Line 9: We use the is.matrix() function, we check to see if the object, myvector, is a matrix object or not.

Free Resources