r - R中的公式输入错误

标签 r

我正在尝试做一些相对简单的事情。我正在尝试使用 lm() 函数提出回归函数并获取诊断信息。
现在 lm() 函数的输入是一个具有 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

如果你想编写自定义错误消息,你可以按如下方式进行(感谢 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

关于r - R中的公式输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569919/

相关文章:

R 在法线轴上绘制逻辑变换数据(逻辑变换)

r - 如何更改绘图中的文本颜色?

r - 一年中一周的奇怪 R strptime 行为

r - 使用R将时间序列中的事件分组

r - 如果 R 包的许可证 X 是,那么该包中的所有内容都必须在 X 下获得许可吗?

r - 用于在 R 中编写(通用)函数的参数和类

r - tidyverse 中的条件 ntile

r - 用新浪图显示多个因素

r - 如何定义某些行序列中没有 NA 的列?

在 LaTeX 文档中使用 tikzDevice 和 knit 进行 R 绘图