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

如何覆盖{tern}包中count_patients_with_flags函数的自动格式?

解决tern包count_patients_with_flags格式覆盖问题

要实现将输出从10 (50%)改为10/20 (50%)的格式,你可以通过以下两种方法解决:

方法1:正确传递.formats参数

count_patients_with_flags内部调用analyze_flag函数,默认统计项名称为count_fraction,需将.formats以列表形式传递(而非向量),修改后的代码如下:

lyt_adae <- basic_table(show_colcounts = TRUE) %>%
  split_cols_by("ACTARM") %>%
  analyze_num_patients(
    vars = "USUBJID",
    .stats = c("unique", "nonunique"),
    .labels = c(
      unique = "Total number of patients with at least one AE",
      nonunique = "Total number of AEs"
    ),
    .formats = list(unique = format_count_fraction_fixed_dp, nonunique = "xx"),
    show_labels = "hidden"
  ) %>%
  count_patients_with_flags(
    "USUBJID",
    flag_variables = c("fl1", "fl2", "fl3", "fl4"),
    denom = "N_col",
    var_labels = "Total number of patients with at least one",
    show_labels = "visible",
    .formats = list(count_fraction = format_count_fraction)  # 列表形式指定格式函数
  )

result_adae <- build_table(lyt_adae, df = adae)

方法2:构建表格后批量修改格式

如果方法1不生效,可在表格生成后,通过modify_table_styles针对性调整格式:

# 构建原始表格
result_adae <- build_table(lyt_adae, df = adae)

# 修改flag统计行的格式为count/denom (pct)
result_adae_modified <- result_adae %>%
  modify_table_styles(
    style = format_count_fraction,
    locations = cells_body(rows = grep("Total number of patients", row.names(.)))
  )

额外说明

  • format_count_fraction是rtables内置函数,自动将计数、分母、百分比组合为count/denom (pct%)格式。
  • 若需自定义格式(比如调整百分比小数位数),可编写自定义函数替换:
custom_format <- function(x, ...) {
  sprintf("%d/%d (%.1f%%)", x$count, x$denom, x$pct)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:52:41