【问题标题】:Modifying or retrieving latex output of kableExtra修改或检索 kableExtra 的乳胶输出
【发布时间】:2021-01-03 06:37:58
【问题描述】:

有没有办法修改或子集部分 kableExtra 的乳胶代码输出?

例如,给定以下代码的输出:

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

是否可以:

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

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

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

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

【问题讨论】:

    标签: r latex kable kableextra


    【解决方案1】:

    也许这就是你要找的。由于kable 输出是一个字符串,您可以通过字符串工具对其进行操作。使用例如在stringr 包中,您可以编写一个函数来提取\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}
    

    reprex package (v0.3.0) 于 2021-01-03 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多