Created
February 28, 2012 06:27
-
-
Save halpo/1930197 to your computer and use it in GitHub Desktop.
Print a Table in markdown grid format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This functionality is already available in the excellent package
ascii
. You can see it by comparing the output ofmdgridtable(df)
with