blob: af77b505abaf0f09b6cfb764611f7f263f1a0dbc [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(
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 Zhudb04e302015-11-15 16:57:38 -050050}