blob: d9d78d178e64b480c617b95f015643c3faf78a87 [file] [log] [blame]
Hao Zhudb04e302015-11-15 16:57:38 -05001#' Magic mirror that returns kable's attributes
2#'
3#' @param input The output of kable
4#'
5#' @export
6
7magic_mirror <- function(input){
Hao Zhu4adea852015-11-16 16:38:34 -05008 if(!"knitr_kable" %in% attr(input, "class")){
Hao Zhudb04e302015-11-15 16:57:38 -05009 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 Zhu4adea852015-11-16 16:38:34 -050014 kable_info <- magic_mirror_latex(input)
Hao Zhudb04e302015-11-15 16:57:38 -050015 }
16 if (kable_format == "html"){
Hao Zhu4adea852015-11-16 16:38:34 -050017 kable_info <- magic_mirror_html(input)
Hao Zhudb04e302015-11-15 16:57:38 -050018 }
Hao Zhu4adea852015-11-16 16:38:34 -050019 return(kable_info)
Hao Zhudb04e302015-11-15 16:57:38 -050020}
21
22#' Magic mirror for latex tables
23magic_mirror_latex <- function(input){
Hao Zhu4adea852015-11-16 16:38:34 -050024 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 Zhudb04e302015-11-15 16:57:38 -050031 )
Hao Zhu4adea852015-11-16 16:38:34 -050032 # Booktabs
33 kable_info$booktabs <- ifelse(grepl("\\\\toprule", input), TRUE, FALSE)
34 # Align
35 kable_info$align <- gsub("\\|", "", str_match(
Hao Zhudc4b7142015-11-19 10:37:53 -050036 input, paste0("\\\\begin\\{", kable_info$tabular,"\\}.*\\{(.*?)\\}"))[2])
Hao Zhu4adea852015-11-16 16:38:34 -050037 # N of columns
38 kable_info$ncol <- nchar(kable_info$align)
Hao Zhu4adea852015-11-16 16:38:34 -050039 # Caption
40 kable_info$caption <- str_match(input, "caption\\{(.*?)\\}")[2]
Hao Zhudc4b7142015-11-19 10:37:53 -050041 # N of rows
42 kable_info$nrow <- str_count(input, "\\\\\n") -
43 # in the dev version (currently as of 11.2015) of knitr, when longtable is
44 # enabled, caption is moved inside the tabular environment. As a result,
45 # the number of rows should be adjusted.
46 ifelse(
47 kable_info$tabular == "longtable" & !is.na(kable_info$caption) &
48 !str_detect(input, "\\\\begin\\{table\\}\\n\\n\\\\caption"),
49 1,0
50 )
Hao Zhu4adea852015-11-16 16:38:34 -050051 # Contents
52 kable_info$contents <- str_match_all(input, "\n(.*)\\\\\\\\")[[1]][,2]
53 # Column names
54 kable_info$colnames <- str_split(kable_info$contents[1], " \\& ")[[1]]
55 # Row names
56 kable_info$rownames <- str_extract(kable_info$contents, "^[^ &]*")
57 return(kable_info)
Hao Zhudb04e302015-11-15 16:57:38 -050058}