Peng Zhang
Peng Zhang

Reputation: 11

format_xx not to drop 0 after rounding

Many thanks for the development of {tern} package that we really enjoy using such package.

I would like to check with you about format_xx(). the format_value will have different values when utilize different codes. See below

> format_value(0.201,format='xx.xx')
[1] "0.20"
> format_value(0.201,format=format_xx('xx.xx'))
[1] "0.2"

the "0.20" is my preferred format. The reason I asked this question is i'm using analyze_vars for the calculation and formatting.

the current list_valid_format_labels() in 'rtables' do not include the format "xx.x (xx.xx)" I would like to use. So I'm trying to use format_xx in analyze_vars

library(dplyr)
library(rtables)
library(tern)
lyt<-
  
  basic_table()%>%
  
  split_cols_by(var= 'ARM')%>%
  
  analyze_vars(vars='AGE',
               
               .stats = c("mean_sd"),
               .formats = c(
                 "mean_sd" = format_xx("xx.x (xx.xx)")
               ),
               .labels = c(
                 "mean_sd" = "Mean (SD)"
               )
  )


build_table(lyt,pharmaverseadam::adsl)

The results will be

              Placebo     Xanomeline High Dose   Xanomeline Low Dose   Screen Failure
—————————————————————————————————————————————————————————————————————————————————————
Mean (SD)   75.2 (8.59)       74.4 (7.89)            75.7 (8.29)         75.1 (9.7)  

So i'm wondering if there is additional feature that using tern::analyze_vars (where I really like this function to put all the variables into the function with order), with option of .formats to specify the format? That is format_xx() to not dropping 0 at the end.

Upvotes: 1

Views: 99

Answers (1)

edlr
edlr

Reputation: 46

This format is not currently available as a preset in formatters or tern, but you can create a custom format function as follows that should accomplish what you're looking to do:

library(dplyr)
library(rtables)
library(tern)

format_fixed_dp <- function(x, ...) {
    if (any(is.na(x))) {
        "NA"
    } else if (x[1] == 0) {
        "0"
    } else {
        sprintf("%.1f (%.2f)", x[1], x[2])
    }
}

lyt<-
    
    basic_table()%>%
    
    split_cols_by(var= 'ARM')%>%
    
    analyze_vars(vars='AGE',
                 
                 .stats = c("mean_sd"),
                 .formats = c(
                     "mean_sd" = format_fixed_dp
                 ),
                 .labels = c(
                     "mean_sd" = "Mean (SD)"
                 )
    )


build_table(lyt,pharmaverseadam::adsl)
#>               Placebo     Xanomeline High Dose   Xanomeline Low Dose   Screen Failure
#> —————————————————————————————————————————————————————————————————————————————————————
#> Mean (SD)   75.2 (8.59)       74.4 (7.89)            75.7 (8.29)        75.1 (9.70)

Created on 2024-11-07 with reprex v2.1.1

Upvotes: 1

Related Questions