如何去除R语言gtsummary包生成表格(含回归表格)中的前导零以符合APA规范?
Great question—gtsummary is such a powerful tool for flexible table building, and tweaking it to fit APA standards is totally doable with a few targeted functions. Let’s break this down step by step:
Core Tools to Use
The star player here is modify_fmt_fun()—it lets you apply custom formatting rules to specific columns in your table. We’ll pair this with built-in gtsummary formatters and a tiny custom helper function to strip leading zeros.
Step 1: Define a Leading-Zero Remover Helper
First, make a quick function to turn values like 0.85 into .85 by stripping that leading 0:
remove_leading_zero <- function(x) { stringr::str_replace(x, "^0\\.", "\\.") }
This uses stringr (which integrates seamlessly with gtsummary) to target strings starting with 0. and swap them for just ..
Step 2: Format Regression Tables for APA Compliance
Let’s use a linear regression example to put this into action. We’ll handle three key APA-aligned adjustments: coefficients, p-values, and confidence intervals:
library(gtsummary) library(stringr) # Fit a sample regression model my_model <- lm(mpg ~ wt + hp + am, data = mtcars) # Build and format the table to meet APA specs tbl_regression(my_model) %>% # Format coefficients: remove leading zero, keep 2 decimal places modify_fmt_fun( columns = estimate, fun = function(x) remove_leading_zero(fmt_number(x, digits = 2)) ) %>% # Format p-values: APA style (no leading zero, <.001 for tiny values) modify_fmt_fun( columns = p.value, fun = fmt_pvalue, leading_zero = FALSE, # This removes the leading zero for p-values digits = 3, cutoff = 0.001 # Shows "<.001" instead of exact values below this threshold ) %>% # Format confidence intervals: remove leading zeros from both bounds modify_fmt_fun( columns = ci, fun = function(x) { # Split CI into lower/upper bounds, clean, remove zeros, then rejoin ci_parts <- str_split(x, ", ", simplify = TRUE) ci_parts[,1] <- remove_leading_zero(str_remove(ci_parts[,1], "\\(")) ci_parts[,2] <- remove_leading_zero(str_remove(ci_parts[,2], "\\)")) paste0("(", ci_parts[,1], ", ", ci_parts[,2], ")") } )
What This Achieves:
- Coefficients: Transforms
0.56to.56 - P-values: Turns
0.023into.023, and0.0008into<.001 - Confidence Intervals: Converts
(0.12, 0.98)to(.12, .98)
Bonus: Apply to Descriptive Tables
If you’re working with tbl_summary() for descriptive stats, you can reuse the same remove_leading_zero function to format continuous variables. For example:
tbl_summary(mtcars, include = c(mpg, wt)) %>% modify_fmt_fun( columns = stat_0, fun = function(x) remove_leading_zero(x) )
Quick Pro Tips
- Ensure you have the latest version of gtsummary installed—some formatting functions get polished in updates.
- To save time across multiple tables, wrap all these
modify_fmt_fun()calls into a custom function (e.g.,add_apa_format()) that you can reuse with a single line.
内容的提问来源于stack exchange,提问作者veronicalm

