“Pretty” table columns
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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!!!
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.