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

modelsummary包中如何将系数名改为α等数学符号?

解决modelsummary系数重命名为数学符号的问题

方案1:借助gt的markdown渲染

modelsummary输出gt对象后,只需开启系数列的markdown解析,就能识别$包裹的LaTeX数学符号。修改代码如下:

library(modelsummary)
library(gt)

basic_reg <- modelsummary(
  list(reg_basis, reg_basis_ausr),
  stars = TRUE,
  coef_rename = c("$\\alpha$", "a", "b", "c"),  # 用双反斜杠转义LaTeX符号
  gof_omit = 'DF|Deviance|AIC|BIC|Log.Lik.|F|RMSE',
  title = 'Table 1: Basic Regressions',
  notes = list("Std. Errors in parentheses", "In (2) UK, Singapore, USA, China, France, Hong Kong and Luxembourg are removed and robust Std. Errors are added"),
  output = "gt") %>%
  # 对系数名称列启用markdown格式解析
  fmt_markdown(columns = vars(term))

gtsave(basic_reg, filename = "basic_reg.png")

方案2:用text_transform自定义替换

如果方案1不生效,可通过gt的text_transform手动替换系数名:

library(modelsummary)
library(gt)

basic_reg <- modelsummary(
  list(reg_basis, reg_basis_ausr),
  stars = TRUE,
  coef_rename = c("alpha_placeholder", "a", "b", "c"),  # 先设置占位符
  gof_omit = 'DF|Deviance|AIC|BIC|Log.Lik.|F|RMSE',
  title = 'Table 1: Basic Regressions',
  notes = list("Std. Errors in parentheses", "In (2) UK, Singapore, USA, China, France, Hong Kong and Luxembourg are removed and robust Std. Errors are added"),
  output = "gt") %>%
  text_transform(
    locations = cells_body(columns = vars(term)),
    fn = function(x) {
      # 替换占位符为LaTeX数学符号
      x <- gsub("alpha_placeholder", "$\\alpha$", x)
      md(x)  # 转为markdown格式
    }
  )

gtsave(basic_reg, filename = "basic_reg.png")

注意事项

  • 不要使用ggplot的expression()函数,gt的渲染逻辑与ggplot不同,它支持markdown和LaTeX混合语法。
  • 写LaTeX符号时要用双反斜杠\\转义,避免被R解析为转义字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:18:37