File: md_table.R

package info (click to toggle)
r-cran-simplermarkdown 0.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 392 kB
  • sloc: makefile: 2
file content (32 lines) | stat: -rw-r--r-- 1,097 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#' Generate a markdown table from a data.frame
#'
#' @param tab a data frame
#' @param caption text of the caption. When omitted no caption is added to the
#'   table.
#' @param as_character return the table as a character vector. If \code{FALSE}
#'   the table will be written to the standard output. 
#' @param ... unused. 
#'
#' @return
#' Then \code{as_character = FALSE} a character vector with the markdown
#' containing the table is returned.  Otherwise, 
#' nothing is returned; the markdown is then written to the console.
#'
#' @export
#' 
md_table <- function(tab, caption, as_character = FALSE, ...) {
  res <- vector("list", ncol(tab))
  for (i in seq_along(res)) {
    t <- format(tab[[i]])
    t <- format(c(names(tab)[i], t))
    nc <- max(nchar(t))
    line <- paste0(rep("-", nc), collapse ="")
    t <- c(t[1], line, utils::tail(t, -1))
    res[[i]] <- t
  }
  res <- do.call(paste, c("", res, "", sep = "|"))
  if (!missing(caption) && !is.null(caption)) {
    res <- c(paste0(": ", caption), "", res)
  }
  if (as_character) paste0(res, collapse="\n")  else writeLines(res)
}