Search code examples
rlatexkablekableextra

Modifying or retrieving latex output of kableExtra


Is there a way to modify or subset part of the latex code output of kableExtra?

For instance, given the output of the following code:

kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE)

would it be possible to either:

a) directly edit one of the rows (e.g. place "Model" before & mpg & cyl & disp)

b) or, just subset everything between \midrule and \bottomrule but drop everything else

My hope with Option b) above is to write my own latex code around the preformatted rows of the main content of the table such as this:

cat(c("\\begin{table}[!htb]
       \\begin{tabular}{lrrr}
       \\toprule
       Model & MPG & CYL & DISP\\",
       t1, # these are the rows between midrule and bottomrule 
      "\\end{tabular}
       \\end{table}"), file = "my_own.tex") 

Solution

  • Maybe this is what you are looking for. As the kable output is a character string you can manipulate it via string tools. Using e.g. the stringr package you can write a function to extract the part between \midrule and \bottomrule like so:

    library(kableExtra)
    library(stringr)
    
    tbl <- kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE)
    
    get_tbl_body <- function(x) {
      start <- str_locate(tbl, "\\\\midrule")[1]
      end <- str_locate(tbl, "\\\\bottomrule")[2]
      str_sub(x, start, end) 
    }
    t1 <- get_tbl_body(tbl)
    
    cat(c("\\begin{table}[!htb]",
          "\\begin{tabular}{lrrr}",
          "\\toprule",
          "Model & MPG & CYL & DISP\\\\",
          t1, # these are the rows between midrule and bottomrule 
          "\\end{tabular}",
          "\\end{table}"), sep = "\n") 
    #> \begin{table}[!htb]
    #> \begin{tabular}{lrrr}
    #> \toprule
    #> Model & MPG & CYL & DISP\\
    #> \midrule
    #> Mazda RX4 & 21.0 & 6 & 160\\
    #> Mazda RX4 Wag & 21.0 & 6 & 160\\
    #> Datsun 710 & 22.8 & 4 & 108\\
    #> Hornet 4 Drive & 21.4 & 6 & 258\\
    #> Hornet Sportabout & 18.7 & 8 & 360\\
    #> \addlinespace
    #> Valiant & 18.1 & 6 & 225\\
    #> \bottomrule
    #> \end{tabular}
    #> \end{table}
    

    Created on 2021-01-03 by the reprex package (v0.3.0)