Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define argument types for R functions?

Tags:

r

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

like image 700
poundifdef Avatar asked Nov 16 '09 23:11

poundifdef


People also ask

What type of arguments can a function take in R?

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.

How do you use a function as an argument in R?

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.

How many arguments can a function have in R?

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.


1 Answers

stopifnot(is.matrix(x))

like image 51
hadley Avatar answered Oct 15 '22 03:10

hadley