| 1 |
#' Create tables in LaTeX, HTML, Markdown and reStructuredText |
| 2 |
#' |
| 3 |
#' A very simple table generator, and it is simple by design. It is not intended |
| 4 |
#' to replace any other R packages for making tables. The \code{kable()} |
| 5 |
#' function returns a single table for a single data object, and returns a table |
| 6 |
#' that contains multiple tables if the input object is a list of data objects. |
| 7 |
#' The \code{kables()} function is similar to \code{kable(x)} when \code{x} is a |
| 8 |
#' list of data objects, but \code{kables()} accepts a list of \code{kable()} |
| 9 |
#' values directly instead of data objects (see examples below). |
| 10 |
#' |
| 11 |
#' Missing values (\code{NA}) in the table are displayed as \code{NA} by |
| 12 |
#' default. If you want to display them with other characters, you can set the |
| 13 |
#' option \code{knitr.kable.NA}, e.g. \code{options(knitr.kable.NA = '')} to |
| 14 |
#' hide \code{NA} values. |
| 15 |
#' |
| 16 |
#' You can set the option \code{knitr.kable.max_rows} to limit the number of |
| 17 |
#' rows to show in the table, e.g., \code{options(knitr.kable.max_rows = 30)}. |
| 18 |
#' @param x For \code{kable()}, \code{x} is an R object, which is typically a |
| 19 |
#' matrix or data frame. For \code{kables()}, a list with each element being a |
| 20 |
#' returned value from \code{kable()}. |
| 21 |
#' @param format A character string. Possible values are \code{latex}, |
| 22 |
#' \code{html}, \code{pipe} (Pandoc's pipe tables), \code{simple} (Pandoc's |
| 23 |
#' simple tables), \code{rst}, \code{jira}, and \code{org} (Emacs Org-mode). |
| 24 |
#' The value of this argument will be automatically determined if the function |
| 25 |
#' is called within a \pkg{knitr} document. The \code{format} value can also |
| 26 |
#' be set in the global option \code{knitr.table.format}. If \code{format} is |
| 27 |
#' a function, it must return a character string. |
| 28 |
#' @param digits Maximum number of digits for numeric columns, passed to |
| 29 |
#' \code{round()}. This can also be a vector of length \code{ncol(x)}, to set |
| 30 |
#' the number of digits for individual columns. |
| 31 |
#' @param row.names Logical: whether to include row names. By default, row names |
| 32 |
#' are included if \code{rownames(x)} is neither \code{NULL} nor identical to |
| 33 |
#' \code{1:nrow(x)}. |
| 34 |
#' @param col.names A character vector of column names to be used in the table. |
| 35 |
#' @param align Column alignment: a character vector consisting of \code{'l'} |
| 36 |
#' (left), \code{'c'} (center) and/or \code{'r'} (right). By default or if |
| 37 |
#' \code{align = NULL}, numeric columns are right-aligned, and other columns |
| 38 |
#' are left-aligned. If \code{length(align) == 1L}, the string will be |
| 39 |
#' expanded to a vector of individual letters, e.g. \code{'clc'} becomes |
| 40 |
#' \code{c('c', 'l', 'c')}, unless the output format is LaTeX. |
| 41 |
#' @param caption The table caption. By default, it is retrieved from the chunk |
| 42 |
#' option \code{tab.cap}. |
| 43 |
#' @param label The table reference label. By default, the label is obtained |
| 44 |
#' from \code{knitr::\link{opts_current}$get('label')} (i.e., the current |
| 45 |
#' chunk label). To disable the label, use \code{label = NA}. |
| 46 |
#' @param format.args A list of arguments to be passed to \code{\link{format}()} |
| 47 |
#' to format table values, e.g. \code{list(big.mark = ',')}. |
| 48 |
#' @param escape Boolean; whether to escape special characters when producing |
| 49 |
#' HTML or LaTeX tables. When \code{escape = FALSE}, you have to make sure |
| 50 |
#' that special characters will not trigger syntax errors in LaTeX or HTML. |
| 51 |
#' @param ... Other arguments (see Examples and References). |
| 52 |
#' @return A character vector of the table source code. |
| 53 |
#' @seealso Other R packages such as \pkg{huxtable}, \pkg{xtable}, |
| 54 |
#' \pkg{kableExtra}, \pkg{gt} and \pkg{tables} for HTML and LaTeX tables, and |
| 55 |
#' \pkg{ascii} and \pkg{pander} for different flavors of markdown output and |
| 56 |
#' some advanced features and table styles. For more on other packages for |
| 57 |
#' creating tables, see |
| 58 |
#' \url{https://bookdown.org/yihui/rmarkdown-cookbook/table-other.html}. |
| 59 |
#' @note When using \code{kable()} as a \emph{top-level} expression, you do not |
| 60 |
#' need to explicitly \code{print()} it due to R's automatic implicit |
| 61 |
#' printing. When it is wrapped inside other expressions (such as a |
| 62 |
#' \code{\link{for}} loop), you must explicitly \code{print(kable(...))}. |
| 63 |
#' @references See |
| 64 |
#' \url{https://bookdown.org/yihui/rmarkdown-cookbook/kable.html} for some |
| 65 |
#' examples about this function, including specific arguments according to the |
| 66 |
#' \code{format} selected. |
| 67 |
#' @export |
| 68 |
#' @examples d1 = head(iris); d2 = head(mtcars) |
| 69 |
#' # pipe tables by default |
| 70 |
#' kable(d1) |
| 71 |
#' kable(d2[, 1:5]) |
| 72 |
#' # no inner padding |
| 73 |
#' kable(d2, format = 'pipe', padding = 0) |
| 74 |
#' # more padding |
| 75 |
#' kable(d2, format = 'pipe', padding = 2) |
| 76 |
#' kable(d1, format = 'latex') |
| 77 |
#' kable(d1, format = 'html') |
| 78 |
#' kable(d1, format = 'latex', caption = 'Title of the table') |
| 79 |
#' kable(d1, format = 'html', caption = 'Title of the table') |
| 80 |
#' # use the booktabs package |
| 81 |
#' kable(mtcars, format = 'latex', booktabs = TRUE) |
| 82 |
#' # use the longtable package |
| 83 |
#' kable(matrix(1000, ncol=5), format = 'latex', digits = 2, longtable = TRUE) |
| 84 |
#' # change LaTeX default table environment |
| 85 |
#' kable(d1, format = "latex", caption = "My table", table.envir='table*') |
| 86 |
#' # add some table attributes |
| 87 |
#' kable(d1, format = 'html', table.attr = 'id="mytable"') |
| 88 |
#' # reST output |
| 89 |
#' kable(d2, format = 'rst') |
| 90 |
#' # no row names |
| 91 |
#' kable(d2, format = 'rst', row.names = FALSE) |
| 92 |
#' # Pandoc simple tables |
| 93 |
#' kable(d2, format = 'simple', caption = 'Title of the table') |
| 94 |
#' # format numbers using , as decimal point, and ' as thousands separator |
| 95 |
#' x = as.data.frame(matrix(rnorm(60, 1e6, 1e4), 10)) |
| 96 |
#' kable(x, format.args = list(decimal.mark = ',', big.mark = "'")) |
| 97 |
#' # save the value |
| 98 |
#' x = kable(d2, format = 'html') |
| 99 |
#' cat(x, sep = '\n') |
| 100 |
#' # can also set options(knitr.table.format = 'html') so that the output is HTML |
| 101 |
#' |
| 102 |
#' # multiple tables via either kable(list(x1, x2)) or kables(list(kable(x1), kable(x2))) |
| 103 |
#' kable(list(d1, d2), caption = 'A tale of two tables') |
| 104 |
#' kables(list(kable(d1, align = 'l'), kable(d2)), caption = 'A tale of two tables') |
| 105 |
kable = function( |
| 106 |
x, format, digits = getOption('digits'), row.names = NA, col.names = NA, |
| 107 |
align, caption = opts_current$get('tab.cap'), label = NULL, format.args = list(), |
| 108 |
escape = TRUE, ... |
| 109 |
) { |
| 110 |
|
| 111 |
format = kable_format(format) |
| 112 |
# expand align if applicable |
| 113 |
if (!missing(align) && length(align) == 1L && !grepl('[^lcr]', align)) |
| 114 |
align = strsplit(align, '')[[1]] |
| 115 |
|
| 116 |
if (inherits(x, 'list')) { |
| 117 |
format = kable_format_latex(format) |
| 118 |
res = lapply( |
| 119 |
x, kable, format = format, digits = digits, row.names = row.names, |
| 120 |
col.names = col.names, align = align, caption = NA, |
| 121 |
format.args = format.args, escape = escape, ... |
| 122 |
) |
| 123 |
return(kables(res, format, caption, label)) |
| 124 |
} |
| 125 |
|
| 126 |
caption = kable_caption(label, caption, format) |
| 127 |
|
| 128 |
if (!is.matrix(x)) x = as.data.frame(x) |
| 129 |
# show the maximum number of rows if set |
| 130 |
if (is.numeric(nr <- getOption('knitr.kable.max_rows'))) x = head(x, nr) |
| 131 |
if (identical(col.names, NA)) col.names = colnames(x) |
| 132 |
m = ncol(x) |
| 133 |
# numeric columns |
| 134 |
isn = if (is.matrix(x)) rep(is.numeric(x), m) else sapply(x, is.numeric) |
| 135 |
if (missing(align) || (format == 'latex' && is.null(align))) |
| 136 |
align = ifelse(isn, 'r', 'l') |
| 137 |
# rounding |
| 138 |
digits = rep(digits, length.out = m) |
| 139 |
for (j in seq_len(m)) { |
| 140 |
if (is_numeric(x[, j])) x[, j] = round(x[, j], digits[j]) |
| 141 |
} |
| 142 |
if (any(isn)) { |
| 143 |
if (is.matrix(x)) { |
| 144 |
if (is.table(x) && length(dim(x)) == 2) class(x) = 'matrix' |
| 145 |
x = format_matrix(x, format.args) |
| 146 |
} else x[, isn] = format_args(x[, isn], format.args) |
| 147 |
} |
| 148 |
if (is.na(row.names)) row.names = has_rownames(x) |
| 149 |
if (!is.null(align)) align = rep(align, length.out = m) |
| 150 |
if (row.names) { |
| 151 |
x = cbind(' ' = rownames(x), x) |
| 152 |
if (!is.null(col.names)) col.names = tail(c(' ', col.names), ncol(x)) |
| 153 |
if (!is.null(align)) align = c('l', align) # left align row names |
| 154 |
} |
| 155 |
n = nrow(x) |
| 156 |
x = replace_na(to_character(x), is.na(x)) |
| 157 |
if (!is.matrix(x)) x = matrix(x, nrow = n) |
| 158 |
# trim white spaces except those escaped by \ at the end (#2308) |
| 159 |
x = gsub('^\\s+|(?<!\\\\)\\s+$', '', x, perl = TRUE) |
| 160 |
colnames(x) = col.names |
| 161 |
if (format != 'latex' && length(align) && !all(align %in% c('l', 'r', 'c'))) |
| 162 |
stop("'align' must be a character vector of possible values 'l', 'r', and 'c'") |
| 163 |
attr(x, 'align') = align |
| 164 |
# simple tables do not 0-row tables (--- will be treated as an hr line) |
| 165 |
if (format == 'simple' && nrow(x) == 0) format = 'pipe' |
| 166 |
res = do.call( |
| 167 |
paste('kable', format, sep = '_'), |
| 168 |
list(x = x, caption = caption, escape = escape, ...) |
| 169 |
) |
| 170 |
structure(res, format = format, class = 'knitr_kable') |
| 171 |
} |
| 172 |
|
| 173 |
kable_caption = function(label, caption, format) { |
| 174 |
# create a label for bookdown if applicable |
| 175 |
if (is.null(label)) label = opts_current$get('label') |
| 176 |
if (is.null(label)) label = NA |
| 177 |
if (!is.null(caption) && !anyNA(caption) && !anyNA(label)) caption = paste0( |
| 178 |
create_label( |
| 179 |
opts_knit$get('label.prefix')[['table']], |
| 180 |
label, latex = (format == 'latex') |
| 181 |
), caption |
| 182 |
) |
| 183 |
caption |
| 184 |
} |
| 185 |
|
| 186 |
# determine the table format |
| 187 |
kable_format = function(format = NULL) { |
| 188 |
if (missing(format) || is.null(format)) format = getOption('knitr.table.format') |
| 189 |
if (is.null(format)) format = if (is.null(pandoc_to())) switch( |
| 190 |
out_format() %n% 'markdown', |
| 191 |
latex = 'latex', listings = 'latex', sweave = 'latex', |
| 192 |
html = 'html', markdown = 'pipe', rst = 'rst', |
| 193 |
stop('table format not implemented yet!') |
| 194 |
) else if (isTRUE(opts_knit$get('kable.force.latex')) && is_latex_output()) { |
| 195 |
# force LaTeX table because Pandoc's longtable may not work well with floats |
| 196 |
# http://tex.stackexchange.com/q/276699/9128 |
| 197 |
'latex' |
| 198 |
} else 'pipe' |
| 199 |
if (is.function(format)) format = format() |
| 200 |
# backward compatibility with knitr <= v1.28 |
| 201 |
switch(format, pandoc = 'simple', markdown = 'pipe', format) |
| 202 |
} |
| 203 |
|
| 204 |
# if the output is for Pandoc and we want multiple tabular in one table, we |
| 205 |
# should use the latex format instead, because Pandoc does not support Markdown |
| 206 |
# in LaTeX yet https://github.com/jgm/pandoc/issues/2453 |
| 207 |
kable_format_latex = function(format) { |
| 208 |
if (format == 'pipe' && is_latex_output()) 'latex' else format |
| 209 |
} |
| 210 |
|
| 211 |
#' @rdname kable |
| 212 |
#' @export |
| 213 |
kables = function(x, format, caption = NULL, label = NULL) { |
| 214 |
format = kable_format(format) |
| 215 |
format = kable_format_latex(format) |
| 216 |
caption = kable_caption(label, caption, format) |
| 217 |
# in case `x` contains kable()s, make sure all kable()s use the same default format |
| 218 |
opts = options(knitr.table.format = format); on.exit(options(opts), add = TRUE) |
| 219 |
if (!inherits(x, 'list')) stop("'x' must be a list (of kable() values)") |
| 220 |
res = unlist(lapply(x, one_string)) |
| 221 |
res = if (format == 'latex') { |
| 222 |
kable_latex_caption(res, caption) |
| 223 |
} else if (format == 'html' || (format == 'pipe' && is_html_output())) kable_html( |
| 224 |
matrix(paste0('\n\n', res, '\n\n'), 1), caption = caption, escape = FALSE, |
| 225 |
table.attr = 'class="kable_wrapper"' |
| 226 |
) else { |
| 227 |
res = paste(res, collapse = '\n\n') |
| 228 |
if (format == 'pipe') kable_pandoc_caption(res, caption) else res |
| 229 |
} |
| 230 |
structure(res, format = format, class = 'knitr_kable') |
| 231 |
} |
| 232 |
|
| 233 |
# convert to character while preserving dim/dimnames attributes |
| 234 |
to_character = function(x) { |
| 235 |
if (is.character(x)) return(x) |
| 236 |
# format columns individually if x is not a matrix |
| 237 |
if (!is.matrix(x)) { |
| 238 |
for (j in seq_len(ncol(x))) x[, j] = format_args(x[, j]) |
| 239 |
x = as.matrix(x) |
| 240 |
} |
| 241 |
x2 = as.character(x); dim(x2) = dim(x); dimnames(x2) = dimnames(x) |
| 242 |
x2 |
| 243 |
} |
| 244 |
|
| 245 |
# as.data.frame() does not allow duplicate row names (#898) |
| 246 |
format_matrix = function(x, args) { |
| 247 |
nms = rownames(x) |
| 248 |
rownames(x) = NULL |
| 249 |
x = as.matrix(format_args(as.data.frame(x), args)) |
| 250 |
rownames(x) = nms |
| 251 |
x |
| 252 |
} |
| 253 |
|
| 254 |
format_args = function(x, args = list()) { |
| 255 |
args$x = x |
| 256 |
args$trim = TRUE |
| 257 |
replace_na(do.call(format, args), is.na(x)) |
| 258 |
} |
| 259 |
|
| 260 |
replace_na = function(x, which = is.na(x), to = getOption('knitr.kable.NA')) { |
| 261 |
if (is.null(to)) return(x) |
| 262 |
x[which] = to |
| 263 |
x |
| 264 |
} |
| 265 |
|
| 266 |
has_rownames = function(x) { |
| 267 |
!is.null(rownames(x)) && !identical(rownames(x), as.character(seq_len(NROW(x)))) |
| 268 |
} |
| 269 |
|
| 270 |
#' @export |
| 271 |
print.knitr_kable = function(x, ...) { |
| 272 |
if (!(attr(x, 'format') %in% c('html', 'latex'))) cat('\n\n') |
| 273 |
cat(x, sep = '\n') |
| 274 |
} |
| 275 |
|
| 276 |
#' @export |
| 277 |
knit_print.knitr_kable = function(x, ...) { |
| 278 |
x = one_string(c( |
| 279 |
if (!(attr(x, 'format') %in% c('html', 'latex'))) c('', ''), x, '\n' |
| 280 |
)) |
| 281 |
asis_output(x) |
| 282 |
} |
| 283 |
|
| 284 |
kable_latex = function( |
| 285 |
x, booktabs = FALSE, longtable = FALSE, tabular = if (longtable) 'longtable' else 'tabular', |
| 286 |
valign = if (tabular %in% c('tabularx', 'xltabular')) '{\\linewidth}' else '[t]', |
| 287 |
position = '', centering = TRUE, |
| 288 |
vline = getOption('knitr.table.vline', if (booktabs) '' else '|'), |
| 289 |
toprule = getOption('knitr.table.toprule', if (booktabs) '\\toprule' else '\\hline'), |
| 290 |
bottomrule = getOption('knitr.table.bottomrule', if (booktabs) '\\bottomrule' else '\\hline'), |
| 291 |
midrule = getOption('knitr.table.midrule', if (booktabs) '\\midrule' else '\\hline'), |
| 292 |
linesep = if (booktabs) c('', '', '', '', '\\addlinespace') else '\\hline', |
| 293 |
caption = NULL, caption.short = '', table.envir = if (!is.null(caption)) 'table', |
| 294 |
escape = TRUE, ... |
| 295 |
) { |
| 296 |
if (!is.null(align <- attr(x, 'align'))) { |
| 297 |
align = paste(align, collapse = vline) |
| 298 |
align = paste0('{', align, '}') |
| 299 |
} |
| 300 |
centering = if (centering && !is.null(caption)) '\n\\centering' |
| 301 |
# vertical align only if 'caption' is not NULL (may be NA) or 'valign' has |
| 302 |
# been explicitly specified; tabularx and xltabular always use 'valign' |
| 303 |
valign = if ((!is.null(caption) || !missing(valign) || tabular %in% c('tabularx', 'xltabular')) && valign != '') { |
| 304 |
if (grepl('^[[{]', valign)) valign else sprintf('[%s]', valign) |
| 305 |
} else '' |
| 306 |
if (identical(caption, NA)) caption = NULL |
| 307 |
if (position != '') position = paste0('[', position, ']') |
| 308 |
env1 = sprintf('\\begin{%s}%s\n', table.envir, position) |
| 309 |
env2 = sprintf('\n\\end{%s}', table.envir) |
| 310 |
if (caption.short != '') caption.short = paste0('[', caption.short, ']') |
| 311 |
cap = if (is.null(caption)) '' else sprintf('\n\\caption%s{%s}', caption.short, caption) |
| 312 |
|
| 313 |
if (nrow(x) == 0) midrule = "" |
| 314 |
|
| 315 |
linesep = if (nrow(x) > 1) { |
| 316 |
c(rep(linesep, length.out = nrow(x) - 1), '') |
| 317 |
} else rep('', nrow(x)) |
| 318 |
linesep = ifelse(linesep == "", linesep, paste0('\n', linesep)) |
| 319 |
|
| 320 |
x = escape_latex_table(x, escape, booktabs) |
| 321 |
if (!is.character(toprule)) toprule = NULL |
| 322 |
if (!is.character(bottomrule)) bottomrule = NULL |
| 323 |
|
| 324 |
paste(c( |
| 325 |
if (cap_env <- !tabular %in% c('longtable', 'xltabular')) c(env1, cap, centering), |
| 326 |
sprintf('\n\\begin{%s}%s', tabular, valign), align, |
| 327 |
if (!cap_env && cap != '') c(cap, '\\\\'), |
| 328 |
sprintf('\n%s', toprule), '\n', |
| 329 |
if (!is.null(cn <- colnames(x))) { |
| 330 |
cn = escape_latex_table(cn, escape, booktabs) |
| 331 |
paste0(paste(cn, collapse = ' & '), sprintf('\\\\\n%s\n', midrule)) |
| 332 |
}, |
| 333 |
one_string(apply(x, 1, paste, collapse = ' & '), sprintf('\\\\%s', linesep), sep = ''), |
| 334 |
sprintf('\n%s', bottomrule), |
| 335 |
sprintf('\n\\end{%s}', tabular), |
| 336 |
if (cap_env) env2 |
| 337 |
), collapse = '') |
| 338 |
} |
| 339 |
|
| 340 |
# when using booktabs, add {} before [ so that the content in [] won't be |
| 341 |
# treated as parameters of booktabs commands like \midrule: |
| 342 |
# https://github.com/yihui/knitr/issues/1595 |
| 343 |
escape_latex_table = function(x, escape = TRUE, brackets = TRUE) { |
| 344 |
if (escape) x = escape_latex(x) |
| 345 |
if (brackets) x = gsub('^(\\s*)(\\[)', '\\1{}\\2', x) |
| 346 |
x |
| 347 |
} |
| 348 |
|
| 349 |
kable_latex_caption = function(x, caption) { |
| 350 |
paste(c( |
| 351 |
'\\begin{table}\n', sprintf('\\caption{%s}\n', caption), x, '\n\\end{table}' |
| 352 |
), collapse = '') |
| 353 |
} |
| 354 |
|
| 355 |
kable_html = function( |
| 356 |
x, table.attr = getOption('knitr.table.html.attr', ''), caption = NULL, escape = TRUE, ... |
| 357 |
) { |
| 358 |
table.attr = trimws(table.attr) |
| 359 |
# need a space between <table and attributes |
| 360 |
if (nzchar(table.attr)) table.attr = paste('', table.attr) |
| 361 |
align = if (is.null(align <- attr(x, 'align'))) '' else { |
| 362 |
sprintf(' style="text-align:%s;"', c(l = 'left', c = 'center', r = 'right')[align]) |
| 363 |
} |
| 364 |
if (identical(caption, NA)) caption = NULL |
| 365 |
cap = if (length(caption)) sprintf('\n<caption>%s</caption>', caption) else '' |
| 366 |
if (escape) x = html_escape(x) |
| 367 |
one_string(c( |
| 368 |
sprintf('<table%s>%s', table.attr, cap), |
| 369 |
if (!is.null(cn <- colnames(x))) { |
| 370 |
if (escape) cn = html_escape(cn) |
| 371 |
c(' <thead>', ' <tr>', sprintf(' <th%s> %s </th>', align, cn), ' </tr>', ' </thead>') |
| 372 |
}, |
| 373 |
'<tbody>', |
| 374 |
paste( |
| 375 |
' <tr>', |
| 376 |
apply(x, 1, function(z) one_string(sprintf(' <td%s> %s </td>', align, z))), |
| 377 |
' </tr>', sep = '\n' |
| 378 |
), |
| 379 |
'</tbody>', |
| 380 |
'</table>' |
| 381 |
)) |
| 382 |
} |
| 383 |
|
| 384 |
#' Generate tables for Markdown and reST |
| 385 |
#' |
| 386 |
#' This function provides the basis for Markdown and reST tables. |
| 387 |
#' @param x The data matrix. |
| 388 |
#' @param sep.row A length-3 character vector, specifying separators to be |
| 389 |
#' printed before the header, after the header, and at the end of the table |
| 390 |
#' respectively. |
| 391 |
#' @param sep.col The column separator. |
| 392 |
#' @param sep.head The column separator for the header of the table (i.e., the |
| 393 |
#' line with the column names). |
| 394 |
#' @param padding Number of spaces for the table cell padding. |
| 395 |
#' @param align.fun A function to process the separator under the header |
| 396 |
#' according to the alignment. |
| 397 |
#' @return A character vector of the table content. |
| 398 |
#' @noRd |
| 399 |
kable_mark = function(x, sep.row = c('=', '=', '='), sep.col = ' ', padding = 0, |
| 400 |
align.fun = function(s, a) s, rownames.name = '', |
| 401 |
sep.head = sep.col, newline = NULL, ...) { |
| 402 |
# when the column separator is |, replace existing | with its HTML entity |
| 403 |
if (sep.col == '|') for (j in seq_len(ncol(x))) { |
| 404 |
x[, j] = gsub('\\|', '|', x[, j]) |
| 405 |
} |
| 406 |
l = if (prod(dim(x)) > 0) apply(x, 2, function(z) { |
| 407 |
max(nchar(remove_urls(z), type = 'width'), na.rm = TRUE) |
| 408 |
}) else integer(ncol(x)) |
| 409 |
cn = colnames(x) |
| 410 |
if (length(cn) > 0) { |
| 411 |
cn[is.na(cn)] = "NA" |
| 412 |
if (sep.head == '|') cn = gsub('\\|', '|', cn) |
| 413 |
if (grepl('^\\s*$', cn[1L])) cn[1L] = rownames.name # no empty cells for reST |
| 414 |
l = pmax(if (length(l) == 0) 0 else l, nchar(remove_urls(cn), type = 'width')) |
| 415 |
} |
| 416 |
align = attr(x, 'align') |
| 417 |
padding = padding * if (length(align) == 0) 2 else { |
| 418 |
ifelse(align == 'c', 2, 1) |
| 419 |
} |
| 420 |
l = pmax(l + padding, 3) # at least of width 3 for Github Markdown |
| 421 |
s = strrep(sep.row[2], l) |
| 422 |
res = rbind( |
| 423 |
if (!is.na(sep.row[1])) s, cn, if (is.null(align)) s else align.fun(s, align), |
| 424 |
x, if (!is.na(sep.row[3])) s |
| 425 |
) |
| 426 |
res = mat_pad(res, l, align) |
| 427 |
res = add_mark_col_sep(res, sep.col, sep.head) |
| 428 |
if (is.character(newline)) res = gsub('\n', newline, res, fixed = TRUE) |
| 429 |
res |
| 430 |
} |
| 431 |
|
| 432 |
# add column separators to header and body separately |
| 433 |
add_mark_col_sep = function(table, sep.col, sep.head) { |
| 434 |
if (any(dim(table) == 0)) return(table) |
| 435 |
h = paste(table[1, ], collapse = sep.head) # header |
| 436 |
b = table[-1, , drop = FALSE] |
| 437 |
b = apply(b, 1, paste, collapse = sep.col) # body |
| 438 |
c(h, b) |
| 439 |
} |
| 440 |
|
| 441 |
kable_rst = function(x, rownames.name = '\\', ...) { |
| 442 |
kable_mark(x, rownames.name = rownames.name) |
| 443 |
} |
| 444 |
|
| 445 |
# Pandoc's pipe table |
| 446 |
kable_pipe = function(x, caption = NULL, padding = 1, caption.label = 'Table:', ...) { |
| 447 |
if (is.null(colnames(x))) colnames(x) = rep('', ncol(x)) |
| 448 |
res = kable_mark(x, c(NA, '-', NA), '|', padding, align.fun = function(s, a) { |
| 449 |
r = c(l = '^.', c = '^.|.$', r = '.$') |
| 450 |
for (i in seq_along(s)) { |
| 451 |
s[i] = gsub(r[a[i]], ':', s[i]) |
| 452 |
} |
| 453 |
s |
| 454 |
}, ...) |
| 455 |
res = sprintf('|%s|', res) |
| 456 |
kable_pandoc_caption(res, caption, caption.label) |
| 457 |
} |
| 458 |
|
| 459 |
# Pandoc's simple table |
| 460 |
kable_simple = function(x, caption = NULL, padding = 1, ...) { |
| 461 |
tab = kable_mark( |
| 462 |
x, c(NA, '-', if (is_blank(colnames(x))) '-' else NA), |
| 463 |
padding = padding, ... |
| 464 |
) |
| 465 |
# when x has only one column with name, indent by one space so --- won't be |
| 466 |
# treated as an hr line |
| 467 |
if (ncol(x) == 1 && !is.null(colnames(x))) tab = paste0(' ', tab) |
| 468 |
kable_pandoc_caption(tab, caption) |
| 469 |
} |
| 470 |
|
| 471 |
# Jira table |
| 472 |
kable_jira = function(x, caption = NULL, padding = 1, ...) { |
| 473 |
tab = kable_mark(x, c(NA, NA, NA), '|', padding, sep.head = '||', ...) |
| 474 |
if ((n <- length(tab)) == 0) return(tab) |
| 475 |
# remove the line that separates the table header from the table body |
| 476 |
if (n >= 2) tab = tab[-2] |
| 477 |
tab[1] = sprintf('||%s||', tab[1]) |
| 478 |
tab[-1] = sprintf('|%s|', tab[-1]) |
| 479 |
kable_pandoc_caption(tab, caption) |
| 480 |
} |
| 481 |
|
| 482 |
# Emacs Org-mode table |
| 483 |
kable_org = function(x, caption = NULL, padding = 1, caption.label = '#+CAPTION:', ...) { |
| 484 |
has_header = !is.null(colnames(x)) |
| 485 |
res = kable_mark(x, c(NA, '-', NA), '|', padding, align.fun = function(s, a) { |
| 486 |
r = c(l = '<l>', c = '<c>', r = '<r>') |
| 487 |
rbind(r[a], if (has_header) s) |
| 488 |
}, ...) |
| 489 |
if (!is.na(i <- grep('^(---+[|])+---+$', res)[1])) |
| 490 |
res[i] = gsub('|', '+', res[i], fixed = TRUE) |
| 491 |
res = sprintf('|%s|', res) |
| 492 |
kable_pandoc_caption(res, caption, caption.label) |
| 493 |
} |
| 494 |
|
| 495 |
kable_pandoc_caption = function(x, caption, label = 'Table:') { |
| 496 |
if (identical(caption, NA)) caption = NULL |
| 497 |
if (length(caption)) c(paste(label, caption), '', x) else x |
| 498 |
} |
| 499 |
|
| 500 |
# pad a matrix |
| 501 |
mat_pad = function(m, width, align = NULL) { |
| 502 |
n = nrow(m); p = ncol(m) |
| 503 |
res = matrix('', nrow = n, ncol = p) |
| 504 |
if (n * p == 0) return(res) |
| 505 |
stopifnot(p == length(width)) |
| 506 |
side = rep('both', p) |
| 507 |
if (!is.null(align)) side = c(l = 'right', c = 'both', r = 'left')[align] |
| 508 |
apply(m, 2, function(x) max(nchar(x, 'width') - nchar(x, 'chars'))) |
| 509 |
matrix(pad_width(c(m), rep(width, each = n), rep(side, each = n)), ncol = p) |
| 510 |
} |
| 511 |
|
| 512 |
# pad a character vector to width (instead of number of chars), considering the |
| 513 |
# case of width > chars (e.g. CJK chars) |
| 514 |
pad_width = function(x, width, side) { |
| 515 |
if (!all(side %in% c('left', 'right', 'both'))) |
| 516 |
stop("'side' must be 'left', 'right', or 'both'") |
| 517 |
w = width - nchar(x, 'width') |
| 518 |
w1 = floor(w / 2) # the left half of spaces when side = 'both' |
| 519 |
s1 = strrep(' ', pmax(0, w * (side == 'left') + w1 * (side == 'both'))) |
| 520 |
s2 = strrep(' ', pmax(0, w * (side == 'right') + (w - w1) * (side == 'both'))) |
| 521 |
paste0(s1, x, s2) |
| 522 |
} |