我正在尝试做一些相对简单的事情。我想使用lm()
函数来创建一个回归函数,并获取诊断结果。
现在lm()
函数的输入是一个具有formula
类的输入。
如何设计一个函数来测试输入是否为formula
,如果不是,则停止并抛出错误?
我正在尝试做一些相对简单的事情。我想使用lm()
函数来创建一个回归函数,并获取诊断结果。
现在lm()
函数的输入是一个具有formula
类的输入。
如何设计一个函数来测试输入是否为formula
,如果不是,则停止并抛出错误?
class
函数来检查对象是否为公式。> fo <- y ~ x1*x2 # this is formula class
> stopifnot(class(fo)=="formula")
>
> fo <- 1
> stopifnot(class(fo)=="formula") # this not a formula
Error: class(fo) == "formula" is not TRUE
> is.formula <- function(x){
class(x)=="formula"
}
>
> is.formula( y ~ x1*x2)
[1] TRUE
> is.formula(2)
[1] FALSE
formula.test <- function(x){
ifelse( class(x)=="formula",
"This is a formula, you can go ahead!",
stop("This is not a formula, we must stop here."))
}
formula.test(y ~ x1*x2) # this is OK
formula.test("a") # stops execution and throws an error
formula.test(1) # stops execution and throws an error
inherits
。foo <- y ~ x
inherits(foo, "formula")
## [1] TRUE
foo <- 1
if (!inherits(foo, "formula")) stop("foo isn't a formula")
## Error: foo isn't a formula
if
+stop
而不是stopifnot
,因为前者允许您编写自定义错误消息。 - nico