# “Pretty” table columns

Every now and then you might want to make a nice table to include directly in your documents without having to faff about with columns later in excel or word. Typical issues might be the specification of decimal places, converting a value and proportion/SE column into one to take the form of n (x) or a value and CIs into x (x_min – x_max). I needed to do these recently and wrote the following functions to make doing it a bit faster and more productive…

specify_decimal <- function(x, dp){ out <- format(round(x, dp), nsmall=dp) out <- gsub(" ", "", out) out } npropconv <- function(n, perc, dp.n=0, dp.perc=1){ n <- specify_decimal(n, dp.n) perc <- specify_decimal(perc, dp.perc) OUT <- paste(n, " (", perc, ")", sep="") OUT }

valciconv <- function(val, CIlower, CIupper, dp.val=2, dp.CI=2){ val <- specify_decimal(val, dp.val) CIlower <- specify_decimal(CIlower, dp.CI) CIupper <- specify_decimal(CIupper, dp.CI) OUT <- paste(val, " (", CIlower, " - ", CIupper, ")", sep="") OUT }

minp <- function(pvalues, min=0.001){ pv <- as.numeric(pvalues) for(i in 1:length(pv)){ if(pv[i] < min) pvalues[i] <- paste("<", min) } pvalues }

And heres what they do…

> specify_decimal(x=c(0.01, 0.000001), dp=3) [1] "0.010" "0.000" > npropconv(n=7, perc=5, dp.n=0, dp.perc=1) [1] "7 (5.0)" > valciconv(val=7, CIlower=3, CIupper=9, dp.val=2, dp.CI=2) [1] "7.00 (3.00 - 9.00)" > minp(0.00002, min=0.05) [1] "< 0.05" > minp(0.00002, min=0.001) [1] "< 0.001"

Any arguments with beginning with dp specify the number of decimal places for the relevant parameter (i.e. dp.n sets the decimal places for the n parameter). It would make sence to follow specify_decimal with a call to minp to deal with the 0s:

> decim <- specify_decimal(c(0.01, 0.000001),3) > minp(decim, 0.001) [1] "0.010" "< 0.001"

Incidently, although I had p values in mind for minp, it can of course be used with any value at all!

Hope someone finds them handy!!!

I was recently toying around with this too. I found “sprintf(“%.3f”, c(X,Y,Z))” to be the best for guaranteeing you get everything to 3 dp. Especially if you have numbers like 0.00165 etc

Hi Matt,

I’ve done something very similar to this before and i do remember using sprintf then, although I dont remember the reason…perhaps I didnt use format before…