You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断R公式中是否包含特定函数?包开发告警需求

检测公式中的poly()及base/stats包函数调用

要在R包中检测公式是否使用了poly()函数,以及是否调用了base或stats包的函数并发出警告,可以通过递归遍历公式的表达式树实现,具体步骤如下:

实现递归检查函数

编写一个递归函数,遍历公式的表达式结构,识别所有函数调用并进行判断:

# 定义公式检查函数
check_formula_dependencies <- function(formula_expr) {
  # 将公式转换为表达式(若输入为公式对象)
  if (inherits(formula_expr, "formula")) {
    formula_expr <- as.expression(formula_expr)
  }
  
  # 递归遍历表达式的内部函数
  check_expr <- function(expr) {
    if (is.call(expr)) {
      # 提取函数名称
      func_sym <- expr[[1]]
      if (is.symbol(func_sym)) {
        func_name <- as.character(func_sym)
        
        # 检测poly()函数
        if (func_name == "poly") {
          warning("公式中检测到poly()函数调用", call. = FALSE)
        }
        
        # 检测函数是否来自base或stats包
        func_locations <- find(func_name, mode = "function")
        if (any(grepl("^package:base$|^package:stats$", func_locations))) {
          warning("公式中检测到base/stats包的函数调用: ", func_name, call. = FALSE)
        }
      }
      # 递归检查函数的所有参数
      lapply(expr[-1], check_expr)
    }
  }
  
  # 执行检查逻辑
  check_expr(formula_expr)
}

在包中调用检查函数

在你的R包函数中,当接收公式参数时调用上述检查函数即可触发警告:

# 示例包函数
my_analysis_function <- function(formula, data) {
  # 先检查公式中的函数调用
  check_formula_dependencies(formula)
  
  # 后续业务逻辑(如模型拟合等)
  # ...
}

测试示例

# 测试公式
f <- ~ poly(xxx, degree = 2)
# 执行检查
check_formula_dependencies(f)

运行后会输出两个警告:

  • 提示检测到poly()函数调用
  • 提示检测到stats包的poly函数调用

内容的提问来源于stack exchange,提问作者MTMT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 09:20:01