Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 1 | #' Magic mirror that returns kable's attributes |
| 2 | #' |
| 3 | #' @param input The output of kable |
| 4 | #' |
| 5 | #' @export |
| 6 | |
| 7 | magic_mirror <- function(input){ |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 8 | if(!"knitr_kable" %in% attr(input, "class")){ |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 9 | warning("magic_mirror may not be able to produce correct result if the", |
| 10 | " input table is not rendered by knitr::kable. ") |
| 11 | } |
| 12 | kable_format <- attr(input, "format") |
| 13 | if (kable_format == "latex"){ |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 14 | kable_info <- magic_mirror_latex(input) |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 15 | } |
| 16 | if (kable_format == "html"){ |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 17 | kable_info <- magic_mirror_html(input) |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 18 | } |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 19 | return(kable_info) |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 20 | } |
| 21 | |
| 22 | #' Magic mirror for latex tables |
| 23 | magic_mirror_latex <- function(input){ |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 24 | kable_info <- list(tabular = NULL, booktabs = NULL, align = NULL, |
| 25 | ncol=NULL, nrow=NULL, colnames = NULL, rownames = NULL, |
| 26 | caption = NULL, contents = NULL) |
| 27 | # Tabular |
| 28 | kable_info$tabular <- ifelse( |
| 29 | grepl("\\\\begin\\{tabular\\}", input), |
| 30 | "tabular", "longtable" |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 31 | ) |
Hao Zhu | 4adea85 | 2015-11-16 16:38:34 -0500 | [diff] [blame^] | 32 | # Booktabs |
| 33 | kable_info$booktabs <- ifelse(grepl("\\\\toprule", input), TRUE, FALSE) |
| 34 | # Align |
| 35 | kable_info$align <- gsub("\\|", "", str_match( |
| 36 | input, paste0("\\\\begin\\{", kable_info$tabular,"\\}\\{(.*?)\\}"))[2]) |
| 37 | # N of columns |
| 38 | kable_info$ncol <- nchar(kable_info$align) |
| 39 | # N of rows |
| 40 | kable_info$nrow <- str_count(input, "\\\\\n") |
| 41 | # Caption |
| 42 | kable_info$caption <- str_match(input, "caption\\{(.*?)\\}")[2] |
| 43 | # Contents |
| 44 | kable_info$contents <- str_match_all(input, "\n(.*)\\\\\\\\")[[1]][,2] |
| 45 | # Column names |
| 46 | kable_info$colnames <- str_split(kable_info$contents[1], " \\& ")[[1]] |
| 47 | # Row names |
| 48 | kable_info$rownames <- str_extract(kable_info$contents, "^[^ &]*") |
| 49 | return(kable_info) |
Hao Zhu | db04e30 | 2015-11-15 16:57:38 -0500 | [diff] [blame] | 50 | } |