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

如何在R的modelsummary输出中为观测数添加千分位逗号

为modelsummary的观测数添加千分位逗号的正确方法

方法1:修正sprintf格式字符串

你的第二种尝试报错是因为%'.0f是针对浮点数的格式,但nobs是整数类型,sprintf要求整数用%d类格式。把格式改为%'d即可:

library(modelsummary)
library(tibble)

# 构建示例模型
model <- lm(mpg ~ wt + hp, data = mtcars)

# 正确配置gof_map
gm <- tibble::tribble(
    ~raw,            ~clean,       ~fmt,
    "nobs",          "N",          "%'d",
    "adj.r.squared", "Adj. R²",    "%.2f"
)

# 生成模型摘要
modelsummary(model, gof_map = gm)

方法2:使用自定义格式化函数

如果想用自定义函数,确保函数接收单个数值并返回格式化后的字符串,可在gof_map中用匿名函数包裹:

format_nobs <- function(x) {
    format(x, big.mark = ",", scientific = FALSE)
}

gm <- tibble::tribble(
    ~raw,            ~clean,       ~fmt,
    "nobs",          "N",          function(x) format_nobs(x),
    "adj.r.squared", "Adj. R²",    2
)

modelsummary(model, gof_map = gm)

也可以直接在fmt列写匿名函数简化代码:

gm <- tibble::tribble(
    ~raw,            ~clean,       ~fmt,
    "nobs",          "N",          function(x) format(x, big.mark = ",", scientific = FALSE),
    "adj.r.squared", "Adj. R²",    2
)

方法3:全局整数统计量格式化

如果希望所有整数类型的拟合优度统计量都自动添加千分位,可使用format_numeric参数做全局配置:

modelsummary(model, 
             format_numeric = function(x) {
                 if (is.integer(x)) {
                     format(x, big.mark = ",", scientific = FALSE)
                 } else {
                     format(x, digits = 2)
                 }
             })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 18:45:16