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

如何使用modelsummary固定RMarkdown HTML表格的首列?

实现模型汇总表格左侧变量列冻结的方案

要实现横向滚动时固定左侧变量名列,确实可以通过DT包完成,以下是两种可行的修改方案:

方案一:先导出为数据框再用DT渲染

将modelsummary的输出转换为数据框,再通过DT::datatable设置固定列参数:

---
title: "Example Document"
subtitle: ""
output:
  rmarkdown::html_document:
    smart: true
    theme: spacelab
    number_sections: no
    toc: true
    toc_float:
      collapsed: true
    toc_depth: 4
---

```{r echo=FALSE, message=FALSE}
library(modelsummary)
library(purrr)
library(DT)

# 生成模型列表
dv <- mtcars %>% colnames() %>% .[-1]
models <- map(.x = dv, ~formula(paste0(.x, "~ mpg"))) %>% map(~lm(.x, data = mtcars))

# 把模型汇总转为数据框,再用DT渲染并固定左侧列
ms_df <- modelsummary(c(models, models, models), output = "data.frame")

datatable(
  ms_df,
  rownames = FALSE,
  scrollX = TRUE,  # 开启横向滚动
  fixedColumns = list(leftColumns = 1),  # 固定左侧第1列(变量名列)
  options = list(
    dom = 't',  # 仅保留表格主体,隐藏搜索、分页控件(可按需调整)
    pageLength = nrow(ms_df)  # 显示所有行
  )
)
## 方案二:直接用modelsummary的DT输出格式
`modelsummary`支持直接输出DT对象,无需手动转换数据框,代码更简洁:

```r
---
title: "Example Document"
subtitle: ""
output:
  rmarkdown::html_document:
    smart: true
    theme: spacelab
    number_sections: no
    toc: true
    toc_float:
      collapsed: true
    toc_depth: 4
---

```{r echo=FALSE, message=FALSE}
library(modelsummary)
library(purrr)

# 生成模型列表
dv <- mtcars %>% colnames() %>% .[-1]
models <- map(.x = dv, ~formula(paste0(.x, "~ mpg"))) %>% map(~lm(.x, data = mtcars))

# 直接输出为DT并设置固定列
modelsummary(
  c(models, models, models),
  output = "dt",
  options = list(
    scrollX = TRUE,
    fixedColumns = list(leftColumns = 1),
    dom = 't',
    pageLength = nrow(modelsummary(c(models, models, models), output = "data.frame"))
  )
)
### 关键参数说明
- `fixedColumns = list(leftColumns = 1)`:指定固定左侧第1列(变量名列)
- `scrollX = TRUE`:当表格宽度超出页面时,开启横向滚动功能
- `dom = 't'`:简化DT控件,只保留表格主体;若需要分页、搜索功能,可改为`dom = 'lfrtip'`

内容的提问来源于stack exchange,提问作者John-Henry
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:01:12