Mohamed Yusuf
Mohamed Yusuf

Reputation: 428

Use scientific notation in p-value produced by gtsummary table

I am trying to display the p-value of a test produced in a gtsummary table in scientific format. So I want my p-value's to look like 2e-16 instead of <0.001. See table below.

Any suggestions how I can do this using the gtsummary package? I have put together a reproducible code below:

# download pacman package if not installed, otherwise load it
if(!require(pacman)) install.packages(pacman)

# loads relevant packages using the pacman package
pacman::p_load(
  tidyverse, # for pipes
  gtsummary) # for tables

# 2by2 table 
trial %>%
  tbl_cross(row = trt, 
            col = response) %>% 
  add_p()

enter image description here

Upvotes: 1

Views: 710

Answers (2)

Bryan
Bryan

Reputation: 68

You could also use

trial %>%
  tbl_cross(row = trt, 
            col = response) %>% 
  add_p() %>%
  modify_table_styling(
    columns = p.value,
    rows = p.value < 0.001,
    fmt_fun = scales::scientific
  )

Upvotes: 1

Daniel D. Sjoberg
Daniel D. Sjoberg

Reputation: 11679

Here's how you can get the p-value you're looking for!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.4.1'

# 2by2 table 
tbl <-
  trial %>%
  tbl_cross(row = trt, 
            col = response) %>% 
  add_p() %>%
  modify_fmt_fun(p.value ~ function(x) ifelse(is.na(x), NA, format(x, digits = 2, scientific = TRUE)))

enter image description here Created on 2021-06-11 by the reprex package (v2.0.0)

The add_p() function has argument pvalue_fun= that should specify the function that formats/styles. But I see that the argument is being ignored (I'll fix this in the next version).

Upvotes: 1

Related Questions