Skip to content

Instantly share code, notes, and snippets.

@karthik
Created October 15, 2012 11:07
Show Gist options
  • Save karthik/3891966 to your computer and use it in GitHub Desktop.
Save karthik/3891966 to your computer and use it in GitHub Desktop.
a function to generate Pandoc compatible markdown tables from R
#' A function to generate markdown tables for R data
#'
#' This function willl generate pandoc compatible markdown for tables from R data
#' @param df a \code{data.frame}
#' @param headings = NULL headings to use if one desires something other than default \code{data.frame} column names
#' @export
#' @examples \dontrun{
#' markdownTable(mtcars)
#'}
markdownTable <- function(df, headings = NULL) {
if(!is(df, "data.frame"))
stop("markdownTable currently only supports data.frame", call.=F)
if(!is.null(headings) && length(headings)!=ncol(df))
stop("Headings don't match dimentions of data.frame")
# First create column width to the max nchar of each col
max_lengths <- rbind(apply(df, 2, nchar),sapply(names(df), length))
colwidths <- apply(max_lengths, 2, function(x) max(x))
topline <- str_pad("-", (sum(colwidths) + 7), pad="-")
# this line above doesn't work
headings <- str_pad(paste0("*", names(df), "*"), round(max(colwidths)/2), "both")
cat(topline)
# cat the data
cat(headings)
cat(topline)
# More issues remain. I need to pad each row element to the max width of that row.
# Then I need to cat the whole thing to screen all at once.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment