2828# ' Use it to display `0.9 (0.85; 0.95)` as `-10% (-15%; -5%)`.
2929# ' Defaults to `FALSE`.
3030# ' Implies `sign == TRUE`.
31+ # ' @param si Use SI prefixes for the estimate, lower and upper confidence limit.
32+ # ' Defaults to `FALSE`.
33+ # ' Ignored when `percent == TRUE`.
3134# ' @export
3235# ' @importFrom assertthat assert_that is.flag is.number noNA
3336# ' @importFrom stats plogis qnorm
6063# ' format_ci(1, lcl = 1, ucl = 1)
6164format_ci <- function (
6265 estimate , se , lcl , ucl , interval = 0.95 , link = c(" identity" , " log" , " logit" ),
63- max_digit = 4 , percent = FALSE , sign = FALSE , change = FALSE
66+ max_digit = 4 , percent = FALSE , sign = FALSE , change = FALSE , si = FALSE
6467) {
6568 link <- match.arg(link )
6669 assert_that(
67- is.numeric(estimate ), noNA(estimate ), is.number(max_digit ),
70+ is.numeric(estimate ), noNA(estimate ), is.number(max_digit ), is.flag( si ),
6871 is.flag(percent ), noNA(percent ), is.flag(sign ), noNA(sign ), is.flag(change ),
69- noNA(change )
72+ noNA(change ), noNA( si ), noNA( change )
7073 )
7174 if (missing(se )) {
7275 assert_that(
@@ -104,6 +107,18 @@ format_ci <- function(
104107 estimate <- 100 * estimate
105108 lcl <- 100 * lcl
106109 ucl <- 100 * ucl
110+ prefix <- rep(" " , length(estimate ))
111+ } else if (si ) {
112+ magnitude <- log10(estimate ) %/% 3
113+ prefix <- c(
114+ " q" , " r" , " y" , " z" , " a" , " f" , " p" , " n" , " µ" , " m" , " " , " k" , " M" , " G" , " T" ,
115+ " P" , " E" , " Z" , " Y" , " R" , " Q"
116+ )[magnitude + 11 ]
117+ lcl <- lcl / 10 ^ (3 * magnitude )
118+ ucl <- ucl / 10 ^ (3 * magnitude )
119+ estimate <- estimate / 10 ^ (3 * magnitude )
120+ } else {
121+ prefix <- rep(" " , length(estimate ))
107122 }
108123
109124 ci_magnitude <- floor(log10(ucl - lcl )) - 2
@@ -119,8 +134,8 @@ format_ci <- function(
119134 )
120135 magnitude <- pmax(magnitude , ci_range )
121136 fmt <- ifelse(
122- magnitude > = - 7 , sprintf(" %%.%if" , pmax(0 , - magnitude )),
123- sprintf(" %%.%ig" , signif_digit )
137+ magnitude > = - 7 , sprintf(" %%.%if%%4$s " , pmax(0 , - magnitude )),
138+ sprintf(" %%.%ig%%4$s " , signif_digit )
124139 )
125140 if (change || sign ) {
126141 fmt <- gsub(" %" , " %+" , fmt )
@@ -132,6 +147,6 @@ format_ci <- function(
132147 sprintf(" %1$s (%1$s; %1$s)" , fmt ),
133148 round(estimate / 10 ^ magnitude ) * 10 ^ magnitude ,
134149 round(lcl / 10 ^ magnitude ) * 10 ^ magnitude ,
135- round(ucl / 10 ^ magnitude ) * 10 ^ magnitude
150+ round(ucl / 10 ^ magnitude ) * 10 ^ magnitude , prefix
136151 )
137152}
0 commit comments