R – Create Matrix

To check if given object is a Matrix or not in R, call is.matrix() function, and pass the object as argument in the function call.

In this tutorial, we will learn how to check if an object is a matrix or not using is.matrix() function.

Syntax

The syntax of is.matrix() function is

is.matrix(x)

where

ArgumentDescription
xAn R object.

Return Value

is.matrix() returns logical value or TRUE or FALSE. TRUE if the given object x is a matrix, or FALSE if the given object x is not a matrix.

ADVERTISEMENT

Examples

In the following program, we create a matrix and programmatically check if this object is a matrix or not.

example.R

data <- c(2, 4, 7, 5, 10, 1)
A <- matrix(data, nrow = 3, byrow = TRUE)
if (is.matrix(A)) {
  print("A is a matrix.")
} else {
  print("A is not a matrix.")
}

Output

[1] "A is a matrix."

Now, let us take a vector in A, and programmatically check if A is matrix or not using is.matrix() function. Since A is not a matrix, is.matrix(A) must return FALSE.

example.R

A <- c(2, 4, 7, 5, 10, 1)
if (is.matrix(A)) {
  print("A is a matrix.")
} else {
  print("A is not a matrix.")
}

Output

[1] "A is not a matrix."

Conclusion

In this R Tutorial, we learned how to check if a given object is a Matrix or not in R using is.matrix() function, with the help of examples.