繁体   English   中英

修改或检索 kableExtra 的 Z25F7E525B5C0641E1EB1FB3BDEBEB15B5Z output

[英]Modifying or retrieving latex output of kableExtra

有没有办法修改或子集 kableExtra 的 latex 代码 output 的一部分?

例如,给定以下代码的 output:

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

是否有可能:

a) 直接编辑其中一行(例如在 & mpg & cyl & disp 之前放置“模型”)

b) 或者,只是子集 \midrule 和 \bottomrule 之间的所有内容,但删除其他所有内容

我希望上面的选项 b) 是围绕表格主要内容的预格式化行编写我自己的 Z25F7E525B5C0641E1EB1FB3BDEBEB15B5Z 代码,例如:

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") 

也许这就是您正在寻找的。 由于kable output 是一个字符串,您可以通过字符串工具对其进行操作。 使用例如stringr package 您可以编写 function 来提取\midrule\bottomrule之间的部分,如下所示:

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}

代表 package (v0.3.0) 于 2021 年 1 月 3 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM