Skip to content

Instantly share code, notes, and snippets.

@halpo
Created February 28, 2012 06:27
Show Gist options
  • Save halpo/1930197 to your computer and use it in GitHub Desktop.
Save halpo/1930197 to your computer and use it in GitHub Desktop.
Print a Table in markdown grid format.
#' Print a table with text borders.
#' @param df a data.frame or matrix
#'
#' Prints a table with borders of |, -, +, and = which is usefull for
#' formating tables to use with markdown.
#'
#' @importFrom stringr str_c str_length str_dup
#' @importFrom dostats compose
#' @export
#' @examples
#' df <- data.frame(idx=1:26, l=letters, L=LETTERS)
#' mdgridtable(df)
#' mdgridtable(matrix(1:9,3,3))
mdgridtable <-
function(df, ...){
m <- as.matrix(format(df, ...))
cn <- colnames(m)
w <- pmax(aaply(m, 2, compose(max, str_length)),
str_length(cn))
(fmt <- paste("|", paste(" %", w, "s ", sep='', collapse="|"), "|", sep=''))
pf <- function(x){do.call(sprintf, append(as.list(x), list(fmt=fmt)))}
line <- str_c("+-", str_c(laply(w, str_dup, string='-'), collapse="-+-"), "-+")
hline <- str_c("+=", str_c(laply(w, str_dup, string='='), collapse="=+="), "=+")
endl <- '\n'
cat(line,endl)
cat(pf(cn), endl)
cat(hline, endl)
a_ply(m, 1, function(x){
cat(pf(x), endl)
cat(line, endl)
})
invisible(df)
}
@halpo
Copy link
Author

halpo commented Feb 28, 2012

This is to help with printing tables for use with markdown. I use pandoc to convert markdown to html and it can handle the tables formatted this way.

@ramnathv
Copy link

This functionality is already available in the excellent package ascii. You can see it by comparing the output of mdgridtable(df) with

library(ascii)
print(ascii(df, include.rownames = FALSE), type = 'rest')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment