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

如何在模型动态公式调用中访问并存储变量名?

解决方法

要让模型对象中存储实际传入的变量名,你可以通过substitute()函数捕获调用时传入的对象名称,再手动修改模型的call属性,具体实现如下:

修改后的函数示例

run_model <- function(datas){
  # 获取实际传入的变量名并转为字符串
  data_name <- deparse(substitute(datas))
  # 拟合模型
  model <- lm(data = datas, formula = bmi~age)
  # 替换模型call中的参数名为实际变量名
  model$call$data <- as.name(data_name)
  model
}

test <- run_model(nhanes)
test$call

代码说明

  • substitute(datas)会捕获函数调用时传入的实际对象表达式(此处为nhanes),deparse()将其转换为字符串格式。
  • model$call$data <- as.name(data_name)把模型call属性里的datas替换为实际传入的变量名,执行后test$call会返回lm(formula = bmi ~ age, data = nhanes)。

如果需要额外存储变量名到模型的自定义属性中,可参考以下写法:

run_model <- function(datas){
  data_name <- deparse(substitute(datas))
  model <- lm(data = datas, formula = bmi~age)
  # 添加自定义属性存储变量名
  attr(model, "data_source") <- data_name
  # 修改call显示
  model$call$data <- as.name(data_name)
  model
}

# 查看自定义属性
attr(test, "data_source")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:42:09