blob: 3c136585e24ab0c278ee2227bdc55364ac764e4e [file] [log] [blame]
Hao Zhu76f0eb62018-09-15 12:38:33 -04001#' Convert xtable to a kable object
2#'
3#' @description This function allow users to turn an xtable object into a kable
4#' so they can use most of kableExtra's functions with their xtable code without
5#' making too many changes. Note that although I tested many cases and it seems
6#' to work, this function may not be functional in some other cases. I'm not
7#' a regular xtable user and can only provide very limited support for this
8#' function.
9#'
10#' You should use this table in the same way as `print.xtable`. All the options
11#' you provided to this function will be sent to `print.xtable`. Instead of
12#' printing out the result, this function will return the LaTeX or HTML as
13#' text and a kable object.
14#'
15#' @param x an xtable object
16#' @param ... options for print.xtable
17#'
18#' @examples
19#' \dontrun{
20#' library(xtable)
21#' xtable(mtcars) %>%
22#' xtable2kable(booktabs = TRUE) %>%
23#' kable_styling(latex_options = "striped")
24#' }
25#'
26#' @export
27xtable2kable <- function(x, ...) {
28 if (!class(x)[1] == "xtable") {
29 warning("x is not an xtable object.")
30 return(x)
31 }
32
33 out <- capture.output(print(x, ...))[-(1:2)]
34 out <- paste(out, collapse = "\n")
35
36 xtable_print_options <- list(...)
37 if ("type" %in% names(xtable_print_options) &&
38 xtable_print_options$type == "html") {
39 out <- structure(out, format = "html", class = "knitr_kable")
40 return(out)
41 }
42
43 out <- structure(out, format = "latex", class = "knitr_kable")
44
45 # Assign modefied meta to output
46 out_meta <- magic_mirror(out)
47
48 if ("table.placement" %in% names(xtable_print_options)) {
49 out_meta$valign <- paste0("[", xtable_print_options$table.placement, "]")
50 }
51 if ("tabular.environment" %in% names(xtable_print_options)) {
52 out_meta$tabular <- xtable_print_options$tabular.environment
53 }
Hao Zhu67764aa2019-03-15 11:57:50 -040054 out_meta$xtable <- TRUE
Hao Zhu76f0eb62018-09-15 12:38:33 -040055 attr(out, "kable_meta") <- out_meta
56 return(out)
57}