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

自定义函数生成lm模型后,tbl_regression调用tidy_standardize报错求助

自定义LM模型无法用tidy_standardize计算标准化系数的解决方法

报错原因

tidy_standardize底层依赖parameters::standardize_parameters的refit方法,该方法需要从模型对象中正确提取原始公式和数据集来重新拟合标准化后的模型。但你用字符串拼接公式传入lm()生成的模型,其内部的公式存储和调用环境不符合该函数的预期,导致无法完成重新拟合。

解决方法

方法1:修改自定义函数,生成标准公式对象

把自定义函数里的字符串公式转为formula对象后再传入lm(),这样模型对象会保留正确的公式结构和环境,让standardize_parameters能正常识别:

library(gtsummary)

run_custom_lm <- function(dependent_var, independent_vars, data) {
  # 将字符串转为公式对象
  formula <- as.formula(paste(dependent_var, "~", paste(independent_vars, collapse = "+")))
  lm_model <- lm(formula, data = data)
  return(lm_model)
}

# 重新生成模型并生成表格
model_custom_fun <- run_custom_lm("mpg", c("hp", "wt", "qsec"), data = mtcars)
tbl_regression(model_custom_fun, tidy_fun = tidy_standardize) %>% as_kable()

方法2:手动标准化数据后再拟合模型

如果不想修改函数,可以先手动标准化数据集,再用标准化后的数据拟合模型,此时模型系数本身就是标准化后的结果,无需调用tidy_standardize:

library(gtsummary)
library(dplyr)

# 标准化目标变量和自变量
mtcars_std <- mtcars %>%
  mutate(across(c(mpg, hp, wt, qsec), ~scale(.) %>% as.vector()))

# 用标准化数据拟合模型
model_custom_std <- run_custom_lm("mpg", c("hp", "wt", "qsec"), data = mtcars_std)

# 直接生成表格
tbl_regression(model_custom_std) %>% as_kable()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:07:04