Skip to content

“Pretty” table columns

April 10, 2014

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)

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="")
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="")
minp <- function(pvalues, min=0.001){
  pv <- as.numeric(pvalues)
  for(i in 1:length(pv)){
    if(pv[i] < min) pvalues[i] <- paste("<", min)

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!!!


From → R

  1. 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…

Trackbacks & Pingbacks

  1. “Pretty” table columns ← Patient 2 Earn
  2. “Pretty” table columns 2 | Insights of a PhD student

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: