如何为R函数定义参数类型?

pou*_*def 12 r

我正在写一个R函数,我想确保我的R函数的参数是某个类(例如,"矩阵").

做这个的最好方式是什么?

假设我有一个函数"foo"来计算矩阵的逆矩阵:

foo <- function(x)
{
   # I want to make sure x is of type "matrix"
   solve(x)
}
Run Code Online (Sandbox Code Playgroud)

我怎么能说 - 正如你可能在C中 - function(matrix x)表示" x必须是类型matrix,如果不是,那么返回错误"?

Sha*_*ane 14

你可以检查它是is.matrix的矩阵,还是在传递参数后用as.matrix转换它:

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)
}
Run Code Online (Sandbox Code Playgroud)


had*_*ley 12

stopifnot(is.matrix(x))