Search code examples
rroundingnaconfidence-interval

Rounding values to 2 digits and excluding NA in calculations


I want to run a table 1 function in R that excludes missing values in the calculations and also rounds the digits to 1 decimal place.

This is my code which excludes the NA in the calculations but I don't know how to round to 1 decimal place.

table1(~.|adulttab$Sex.x, data=adulttab[-1],render.categorical ="FREQ (PCTnoNA%)",
   render.continuous=c(.="Mean [SD]",.="Median [Q25, Q75]",.="Min, Max"))

Also is there a way to include confidence intervals in the table1?


Solution

  • You could try something like this:

    rndr.cont <- function(x, ...) {
        s  <- lapply(stats.default(x, ...), round_pad, digits=1)
        CI <- round_pad(t.test(x)$conf.int, digits=1)
        with(s, c("", 
                "Mean [SD]"         = sprintf("%s [%s]",     MEAN, SD),
                "95% CI"            = sprintf("(%s, %s)",    CI[1], CI[2]),
                "Median [Q25, Q75]" = sprintf("%s [%s, %s]", MEDIAN, q25, q75),
                "Min, Max"          = sprintf("%s, %s",      MIN, MAX)
        ))
    }
    
    table1(~.|adulttab$Sex.x, data=adulttab[-1],render.categorical ="FREQ (PCTnoNA%)",
       render.continuous=rndr.cont)