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

在R的gt包中能否同时合并列并格式化置信区间数据?

在gt包内同时实现列合并与数据格式化的方法

有两种可行的方法可以在gt包内直接完成置信区间上下限列的格式化与合并,无需修改原始数据集:

方法一:先格式化列,再合并

先使用fmt_number对上下限列做数值格式化,再用cols_merge合并已格式化的内容:

library(gt)
library(tibble)

df <- tibble(upper_bounds = c(0.00000123, 0.2323223),
             lower_bounds = c(0.12334455, 0.1234556))

tab <- df %>%
  gt() %>%
  fmt_number(columns = c(upper_bounds, lower_bounds), decimals = 3) %>%
  cols_merge(
    columns = c(lower_bounds, upper_bounds),
    pattern = "({1}, {2})"
  )

cols_merge会直接调用之前格式化好的文本结果,最终生成带指定小数位数的置信区间字符串。

方法二:用自定义函数合并并格式化

使用cols_merge_with_func传入自定义函数,在函数内部同时完成数值格式化与拼接:

tab <- df %>%
  gt() %>%
  cols_merge_with_func(
    columns = c(lower_bounds, upper_bounds),
    fn = function(lower, upper) {
      # 格式化上下限为3位小数
      lower_fmt <- format(round(lower, 3), nsmall = 3)
      upper_fmt <- format(round(upper, 3), nsmall = 3)
      # 拼接成置信区间格式
      paste0("(", lower_fmt, ", ", upper_fmt, ")")
    }
  )

这种方法一步完成格式化与合并逻辑,适合需要更灵活自定义格式的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:40:03