I am writing an R function, and I want to make sure that the argument of my R function is of a certain class (eg, "matrix").
What is the best way to do this?
Say I have a function "foo" which computes the inverse of a matrix:
foo <- function(x)
{
# I want to make sure x is of type "matrix"
solve(x)
}
How can I say - as you might in C - function(matrix x)
to denote that "x
must be of type matrix
, and if it isn't, then return an error"?
Function arguments in R can have default values. Default arguments can even be defined in terms of variables created within the function. This is used frequently in base R functions, but I think it is bad practice, because you can't understand what the default values will be without reading the complete source code.
Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.
R functions can have many arguments (the default plot function has 16). Function definitions can allow arguments to take default values so that users do not need to provide values for every argument.
stopifnot(is.matrix(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With