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 objectsmymatrix <- 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 matrixis.matrix(mymatrix)is.matrix(myvector)# obtaining their dim attributedim(mymatrix)dim(myvector)
Explanation
- Line 2: We create an R object,
mymatrix, using thematrix()function. - Line 3: We create another R object,
myvector. - Line 6: We implement the
is.matrix()function on the object,mymatrixto see if it's a matrix or not. - Line 7: We implement the
is.matrix()function on the object,myvectorto see if it's a matrix or not. - Line 10–11: We check the
dimattribute of both objects.
Note: The attributedimfor the object,myvector, is not of length2, unlike the other matrix object with a length of2. To makemyvectorinto a matrix object, we only need to pass thedimattribute.
Example
# creating R objectsmymatrix <- 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 objectdim(myvector) <- c(2,3)# Now check to see if it is a matrix object or notis.matrix(myvector)
Code explanation
- Line 2: We create an R object,
mymatrix, using thematrix()function. - Line 3: We create another R object,
myvector. - Line 6: We use the
dimattribute, we passed a dimension of2by3to the object to make it a matrix withdimattribute of length2. - Line 9: We use the
is.matrix()function, we check to see if the object,myvector, is a matrix object or not.