如何使用 escape = FALSE 在 kableExtra 函数中强制换行?

Wes*_*pse 5 latex r r-markdown kableextra kable

在 kableExtra >= 0.8.0 中,将换行符插入到从 kableExtra 函数(例如or )通过管道输送到表中的文本中的规范方法是直接添加。add_header_abovepack_rows\n

但是,这似乎不适用于该escape = FALSE参数,如果文本还包含 LaTeX 代码,则需要该参数。

如何使用 强制在 kableExtra 函数中换行escape = FALSE

library(dplyr)
library(knitr)
library(kableExtra)

starwars %>%
  filter(species == 'Gungan' | species == 'Droid') %>%
  arrange(species) %>%
  select(name, eye_color) %>%
  kbl(booktabs = TRUE) %>%
  pack_rows(
    index = c(
      'The droids: everybody\'s favourite' = 6, 
      'The Gungans: only beloved of \nthose aged under $3^2$' = 3), 
    escape = FALSE)
Run Code Online (Sandbox Code Playgroud)

Mat*_*lke 3

问题

当前的问题是您希望转义标头的一部分(即中断)而不是转义另一部分(即数学代码)。

进一步的并发症

这个核心问题因许多因素而变得更加复杂:

  1. kableExtra 何时以及如何编程来处理转义
  2. 渴望有一个同时适用于 html 和 LaTeX 输出的解决方案
  3. R 何时以及如何计算代码

一个办法

这是一个适用于 html 和 LaTeX 输出的解决方案,但它不像原始代码那样干净和直接:

# a new version of `kableExtra::linebreak()` that takes into account what type 
# of output is desired as well as how much escaping is necessary
linebreak2 <- function(x, double_escape = TRUE, ...) {
  # if LaTeX insert text into a `\makecell[]{}` command and double escape
  if(knitr::is_latex_output())
    return(linebreak(x, double_escape = double_escape, ...))
  
  # if html output just replace `\n`s with `<br/>`s
  if(knitr::is_html_output())
    return(gsub("\n", "<br/>", x))
  
  # let x pass through for other types of output
  return(x)
}

# build the index named vector outside the pipe flow 
# in order to set the names using `linebreak2()`
index <- c(6, 3)
names(index) <- c(
  'The droids: everybody\'s favourite',
  linebreak2('The Gungans: only beloved of \nthose aged under $3^2$')
)

# proceed as before
starwars %>%
  filter(species == 'Gungan' | species == 'Droid') %>%
  arrange(species) %>%
  select(name, eye_color) %>%
  kbl(booktabs = TRUE) %>%
  pack_rows(index = index, escape = FALSE)
Run Code Online (Sandbox Code Playgroud)

PDF输出

在此输入图像描述

HTML 输出

在此输入图像描述