Check if a matrix is valid and if it meets specified conditions
Source:R/check_matrix.R
check-matrix.Rd
check_matrix()
and check_is_matrix()
functions validate
whether a given object is a matrix and, optionally, whether it meets
conditions such as the number of rows, columns, and whether it is
square. The check_matrix()
function raises an error if the
conditions are not met, while check_is_matrix()
returns
TRUE
if the matrix is valid and meets the conditions, and
FALSE
otherwise.
Usage
check_matrix(
mat,
nrows = NULL,
ncols = NULL,
is_numeric = TRUE,
is_square = FALSE,
par_name = "mat"
)
check_is_matrix(
mat = mat,
nrows = NULL,
ncols = NULL,
is_numeric = TRUE,
is_square = FALSE
)
Arguments
- mat
The object to check.
- nrows
The expected number of rows.
- ncols
The expected number of columns.
- is_numeric
A logical value indicating whether the matrix should contain numeric values.
- is_square
A logical value indicating whether the matrix should be square (i.e., same number of rows and columns).
- par_name
An optional name of the parameter to display in error messages.
Value
check_matrix()
: Returns the matrix if valid, otherwise raises an error message.check_is_matrix()
: Logical value,TRUE
if the matrix meets the specified conditions, andFALSE
otherwise.
Examples
# Examples for check_matrix()
# ----------------------------
mat1 <- matrix(1:9, nrow = 3)
print(mat1)
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
check_matrix(mat1, nrows = 3, ncols = 3)
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
try(check_matrix(mat1, nrows = 3, ncols = 2))
#> Error in check_matrix(mat1, nrows = 3, ncols = 2) :
#> Expected 'mat' to have 2 columns but got 3
mat2 <- matrix(1:9, nrow = 3)
print(mat2)
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
try(check_matrix(mat2, is_square = TRUE))
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
mat3 <- matrix(1:6, nrow = 2)
print(mat3)
#> [,1] [,2] [,3]
#> [1,] 1 3 5
#> [2,] 2 4 6
try(check_matrix(mat3))
#> [,1] [,2] [,3]
#> [1,] 1 3 5
#> [2,] 2 4 6
mat4 <- "Not a matrix"
try(check_matrix(mat4))
#> Error in check_matrix(mat4) :
#> Expected 'mat' to be a matrix but got character
# Examples for check_is_matrix()
# ------------------------------
check_is_matrix(mat1, nrows = 3, ncols = 3)
#> [1] TRUE
check_is_matrix(mat1, nrows = 3, ncols = 2)
#> [1] FALSE
check_is_matrix(mat2, is_square = TRUE)
#> [1] TRUE
check_is_matrix(mat3)
#> [1] TRUE
check_is_matrix(mat4)
#> [1] FALSE