tags:

views:

248

answers:

3

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"?

+5  A: 

You can either check that it's a matrix with is.matrix or else convert it with as.matrix after the parameter is passed:

foo <- function(x)
{
   if(!is.matrix(x)) stop("x must be a matrix")
   # I want to make sure x is of type "matrix"
   solve(x)
}
Shane
Okay, cool. I was just completely oblivious to "is.matrix". Thanks!
rascher
Essentially every datatype has an *is* and *as* function.
Shane
+3  A: 

Just for completeness: besides

is.matrix(foo)

you can also test for

class(foo) == "matrix"

which also works for non-standard that do not have is.foo() functions.

Dirk Eddelbuettel
Have to be careful here, since objects in R might have more than one class. So the code should read "matrix"%in%class(foo).
Eduardo Leoni
Agreed, thanks!
Dirk Eddelbuettel
Or use `inherits`
hadley
+4  A: 

stopifnot(is.matrix(x))

hadley