How to define argument types for R functions?

前端 未结 3 1360
名媛妹妹
名媛妹妹 2021-02-14 00:30

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?

S

相关标签:
3条回答
  • 2021-02-14 01:02

    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.

    0 讨论(0)
  • 2021-02-14 01:03

    stopifnot(is.matrix(x))

    0 讨论(0)
  • 2021-02-14 01:07

    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)
    }
    
    0 讨论(0)
提交回复
热议问题