R Basic

is.matrix() Function: Check If an Object is a Matrix in R

The is.matrix() is a built-in R function that checks whether an input object is a matrix. It returns TRUE if the object is a matrix and FALSE otherwise.

To prevent unexpected errors, you need to check if the input object is a matrix, and that’s where we need this function. It makes our code more predictable and reliable.

Syntax

is.matrix(obj)

Parameters

Name Value
obj It is an input variable that will be checked for a matrix.

Visual representation

Checking matrix

Let’s define a 3X3 matrix.

mat <- matrix(1:9, nrow = 3, ncol = 3)

mat # 3x3 matrix

is.matrix(mat) # TRUE

Output

If you pass a vector as an argument, it will return FALSE.

vec <- c(1, 2, 3)

is.matrix(vec) # FALSE

Usage with a conditional statement

Conditional statements like “if” can be used with is.matrix() function to check if it is a matrix, and if yes, then we can use the “apply()” function to it.

mat <- matrix(1:9, nrow = 3, ncol = 3)

col_means <- function(mtrx) {
  if (!is.matrix(mtrx)) {
    stop("Input must be a matrix")
  }
  apply(mtrx, 2, mean)
}

col_means(mat)

Output

[1] 2  5  8

Since the input object is a matrix, we used the apply() function to get the mean of each column.

If the input object is not a matrix, it stops and prints an error message.

Checking NA values

NA represents missing values, and missing values can be anything. If a matrix contains NA values, is.matrix() function returns TRUE.

mat_with_na <- matrix(c(19, 21, NA, 10), nrow = 2)

is.matrix(mat_with_na) # TRUE

If you pass the NA value to this function, it returns FALSE.

na_val <- NA

is.matrix(na_val) # FALSE

Checking NaN (Not a Number)

NaN represents undefined numerical results. (e.g., 0/0, Inf – Inf). If a matrix contains NaN, it still returns TRUE.

mat_with_nan <- matrix(c(19, 21, NaN, 10), nrow = 2)

is.matrix(mat_with_nan) # TRUE

If you pass the NaN value to this function, it returns FALSE.

nan_val <- NaN

is.matrix(nan_val) # FALSE

That’s all!

Recent Posts

R scale(): Scaling and Centering of Matrix-like Objects

The scale() function in R centers (subtracting the mean) and/or scales (dividing by the standard…

2 weeks ago

file.rename(): Renaming Single and Multiple Files in R

To rename a file in R, you can use the file.rename() function. It renames a…

3 weeks ago

R prop.table() Function

The prop.table() function in R calculates the proportion or relative frequency of values in a…

3 weeks ago

exp() Function: Calculate Exponential of a Number in R

The exp() is a built-in function that calculates the exponential of its input, raising Euler's…

3 weeks ago

R split() Function: Splitting a Data

The split() function divides the input data into groups based on some criteria, typically specified…

1 month ago

colMeans(): Calculating the Mean of Columns in R Data Frame

The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…

1 month ago