#' Create tables in LaTeX, HTML, Markdown and reStructuredText #' #' A very simple table generator, and it is simple by design. It is not intended #' to replace any other R packages for making tables. The \code{kable()} #' function returns a single table for a single data object, and returns a table #' that contains multiple tables if the input object is a list of data objects. #' The \code{kables()} function is similar to \code{kable(x)} when \code{x} is a #' list of data objects, but \code{kables()} accepts a list of \code{kable()} #' values directly instead of data objects (see examples below). #' #' Missing values (\code{NA}) in the table are displayed as \code{NA} by #' default. If you want to display them with other characters, you can set the #' option \code{knitr.kable.NA}, e.g. \code{options(knitr.kable.NA = '')} to #' hide \code{NA} values. #' #' You can set the option \code{knitr.kable.max_rows} to limit the number of #' rows to show in the table, e.g., \code{options(knitr.kable.max_rows = 30)}. #' @param x For \code{kable()}, \code{x} is an R object, which is typically a #' matrix or data frame. For \code{kables()}, a list with each element being a #' returned value from \code{kable()}. #' @param format A character string. Possible values are \code{latex}, #' \code{html}, \code{pipe} (Pandoc's pipe tables), \code{simple} (Pandoc's #' simple tables), \code{rst}, \code{jira}, and \code{org} (Emacs Org-mode). #' The value of this argument will be automatically determined if the function #' is called within a \pkg{knitr} document. The \code{format} value can also #' be set in the global option \code{knitr.table.format}. If \code{format} is #' a function, it must return a character string. #' @param digits Maximum number of digits for numeric columns, passed to #' \code{round()}. This can also be a vector of length \code{ncol(x)}, to set #' the number of digits for individual columns. #' @param row.names Logical: whether to include row names. By default, row names #' are included if \code{rownames(x)} is neither \code{NULL} nor identical to #' \code{1:nrow(x)}. #' @param col.names A character vector of column names to be used in the table. #' @param align Column alignment: a character vector consisting of \code{'l'} #' (left), \code{'c'} (center) and/or \code{'r'} (right). By default or if #' \code{align = NULL}, numeric columns are right-aligned, and other columns #' are left-aligned. If \code{length(align) == 1L}, the string will be #' expanded to a vector of individual letters, e.g. \code{'clc'} becomes #' \code{c('c', 'l', 'c')}, unless the output format is LaTeX. #' @param caption The table caption. By default, it is retrieved from the chunk #' option \code{tab.cap}. #' @param label The table reference label. By default, the label is obtained #' from \code{knitr::\link{opts_current}$get('label')} (i.e., the current #' chunk label). To disable the label, use \code{label = NA}. #' @param format.args A list of arguments to be passed to \code{\link{format}()} #' to format table values, e.g. \code{list(big.mark = ',')}. #' @param escape Boolean; whether to escape special characters when producing #' HTML or LaTeX tables. When \code{escape = FALSE}, you have to make sure #' that special characters will not trigger syntax errors in LaTeX or HTML. #' @param ... Other arguments (see Examples and References). #' @return A character vector of the table source code. #' @seealso Other R packages such as \pkg{huxtable}, \pkg{xtable}, #' \pkg{kableExtra}, \pkg{gt} and \pkg{tables} for HTML and LaTeX tables, and #' \pkg{ascii} and \pkg{pander} for different flavors of markdown output and #' some advanced features and table styles. For more on other packages for #' creating tables, see #' \url{https://bookdown.org/yihui/rmarkdown-cookbook/table-other.html}. #' @note When using \code{kable()} as a \emph{top-level} expression, you do not #' need to explicitly \code{print()} it due to R's automatic implicit #' printing. When it is wrapped inside other expressions (such as a #' \code{\link{for}} loop), you must explicitly \code{print(kable(...))}. #' @references See #' \url{https://bookdown.org/yihui/rmarkdown-cookbook/kable.html} for some #' examples about this function, including specific arguments according to the #' \code{format} selected. #' @export #' @examples d1 = head(iris); d2 = head(mtcars) #' # pipe tables by default #' kable(d1) #' kable(d2[, 1:5]) #' # no inner padding #' kable(d2, format = 'pipe', padding = 0) #' # more padding #' kable(d2, format = 'pipe', padding = 2) #' kable(d1, format = 'latex') #' kable(d1, format = 'html') #' kable(d1, format = 'latex', caption = 'Title of the table') #' kable(d1, format = 'html', caption = 'Title of the table') #' # use the booktabs package #' kable(mtcars, format = 'latex', booktabs = TRUE) #' # use the longtable package #' kable(matrix(1000, ncol=5), format = 'latex', digits = 2, longtable = TRUE) #' # change LaTeX default table environment #' kable(d1, format = "latex", caption = "My table", table.envir='table*') #' # add some table attributes #' kable(d1, format = 'html', table.attr = 'id="mytable"') #' # reST output #' kable(d2, format = 'rst') #' # no row names #' kable(d2, format = 'rst', row.names = FALSE) #' # Pandoc simple tables #' kable(d2, format = 'simple', caption = 'Title of the table') #' # format numbers using , as decimal point, and ' as thousands separator #' x = as.data.frame(matrix(rnorm(60, 1e6, 1e4), 10)) #' kable(x, format.args = list(decimal.mark = ',', big.mark = "'")) #' # save the value #' x = kable(d2, format = 'html') #' cat(x, sep = '\n') #' # can also set options(knitr.table.format = 'html') so that the output is HTML #' #' # multiple tables via either kable(list(x1, x2)) or kables(list(kable(x1), kable(x2))) #' kable(list(d1, d2), caption = 'A tale of two tables') #' kables(list(kable(d1, align = 'l'), kable(d2)), caption = 'A tale of two tables') kable = function( x, format, digits = getOption('digits'), row.names = NA, col.names = NA, align, caption = opts_current$get('tab.cap'), label = NULL, format.args = list(), escape = TRUE, ... ) { format = kable_format(format) # expand align if applicable if (!missing(align) && length(align) == 1L && !grepl('[^lcr]', align)) align = strsplit(align, '')[[1]] if (inherits(x, 'list')) { format = kable_format_latex(format) res = lapply( x, kable, format = format, digits = digits, row.names = row.names, col.names = col.names, align = align, caption = NA, format.args = format.args, escape = escape, ... ) return(kables(res, format, caption, label)) } caption = kable_caption(label, caption, format) if (!is.matrix(x)) x = as.data.frame(x) # show the maximum number of rows if set if (is.numeric(nr <- getOption('knitr.kable.max_rows'))) x = head(x, nr) if (identical(col.names, NA)) col.names = colnames(x) m = ncol(x) # numeric columns isn = if (is.matrix(x)) rep(is.numeric(x), m) else sapply(x, is.numeric) if (missing(align) || (format == 'latex' && is.null(align))) align = ifelse(isn, 'r', 'l') # rounding digits = rep(digits, length.out = m) for (j in seq_len(m)) { if (is_numeric(x[, j])) x[, j] = round(x[, j], digits[j]) } if (any(isn)) { if (is.matrix(x)) { if (is.table(x) && length(dim(x)) == 2) class(x) = 'matrix' x = format_matrix(x, format.args) } else x[, isn] = format_args(x[, isn], format.args) } if (is.na(row.names)) row.names = has_rownames(x) if (!is.null(align)) align = rep(align, length.out = m) if (row.names) { x = cbind(' ' = rownames(x), x) if (!is.null(col.names)) col.names = tail(c(' ', col.names), ncol(x)) if (!is.null(align)) align = c('l', align) # left align row names } n = nrow(x) x = replace_na(to_character(x), is.na(x)) if (!is.matrix(x)) x = matrix(x, nrow = n) # trim white spaces except those escaped by \ at the end (#2308) x = gsub('^\\s+|(? 1) { c(rep(linesep, length.out = nrow(x) - 1), '') } else rep('', nrow(x)) linesep = ifelse(linesep == "", linesep, paste0('\n', linesep)) x = escape_latex_table(x, escape, booktabs) if (!is.character(toprule)) toprule = NULL if (!is.character(bottomrule)) bottomrule = NULL paste(c( if (cap_env <- !tabular %in% c('longtable', 'xltabular')) c(env1, cap, centering), sprintf('\n\\begin{%s}%s', tabular, valign), align, if (!cap_env && cap != '') c(cap, '\\\\'), sprintf('\n%s', toprule), '\n', if (!is.null(cn <- colnames(x))) { cn = escape_latex_table(cn, escape, booktabs) paste0(paste(cn, collapse = ' & '), sprintf('\\\\\n%s\n', midrule)) }, one_string(apply(x, 1, paste, collapse = ' & '), sprintf('\\\\%s', linesep), sep = ''), sprintf('\n%s', bottomrule), sprintf('\n\\end{%s}', tabular), if (cap_env) env2 ), collapse = '') } # when using booktabs, add {} before [ so that the content in [] won't be # treated as parameters of booktabs commands like \midrule: # https://github.com/yihui/knitr/issues/1595 escape_latex_table = function(x, escape = TRUE, brackets = TRUE) { if (escape) x = escape_latex(x) if (brackets) x = gsub('^(\\s*)(\\[)', '\\1{}\\2', x) x } kable_latex_caption = function(x, caption) { paste(c( '\\begin{table}\n', sprintf('\\caption{%s}\n', caption), x, '\n\\end{table}' ), collapse = '') } kable_html = function( x, table.attr = getOption('knitr.table.html.attr', ''), caption = NULL, escape = TRUE, ... ) { table.attr = trimws(table.attr) # need a space between
| %s | ', align, cn), '
|---|
| %s | ', align, z))), '