R中的公式输入错误

3

我正在尝试做一些相对简单的事情。我想使用lm()函数来创建一个回归函数,并获取诊断结果。
现在lm()函数的输入是一个具有formula类的输入。

如何设计一个函数来测试输入是否为formula,如果不是,则停止并抛出错误?

2个回答

2
您可以使用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

如果您想编写自定义错误消息,您可以按照以下步骤操作(感谢nico)
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

+1,尽管我更喜欢使用if + stop而不是stopifnot,因为前者允许您编写自定义错误消息。 - nico

0
另一个选项是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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接