Rmarkdown 乳胶输出:sapply 问题

Rmarkdown latex output: issue with sapply

请参阅下面的 reprex1reprex2lapply 运行但是 sapply 有一个 " 添加到 .tex 文件中第 87 行的开头,破坏它。

想法?

---
title: "reprex"
output:
  pdf_document:
    latex_engine: xelatex
editor_options: 
  chunk_output_type: console
---
{r reprex1, echo=FALSE, warning=FALSE, message=FALSE, results='asis'}

library(tidyverse)
library(kableExtra)

species = c("Human", "Droid")

lapply(species, function(x){
  
  starwars %>%
    select(name, birth_year) %>%
    kable() %>%
  kable_styling(fixed_thead = TRUE, latex_options = c("striped", "scale_down"))%>%
  row_spec(0, bold = TRUE)
})

{r reprex2, echo=FALSE, warning=FALSE, message=FALSE, results='asis'}

library(tidyverse)
library(kableExtra)

species = c("Human", "Droid")

sapply(species, function(x){
  
  starwars %>%
    select(name, birth_year) %>%
    kable() %>%
  kable_styling(fixed_thead = TRUE, latex_options = c("striped", "scale_down"))%>%
  row_spec(0, bold = TRUE)
})

首先,我认为您可能想在函数中添加一行,实际对变量 x 执行某些操作,例如过滤,否则您只会返回两次相同的输出。

sapply(x, f, simplify = FALSE, USE.NAMES = FALSE)lapply(x, f) 相同,因此您可以将下面的 sapply 语句的输出与 simplify = TRUEsimplify = FALSE 进行比较:

library(tidyverse)
library(kableExtra)

species = c("Human", "Droid")

str(sapply(species, function(x){
    starwars %>%
        dplyr::filter(species == x) %>%
        select(name, birth_year) %>%
        kable() %>%
        kable_styling(fixed_thead = TRUE, latex_options = c("striped", "scale_down")) %>%
        row_spec(0, bold = TRUE)
}, simplify = FALSE)[[1]])
#>  'kableExtra' chr "<table class=\"table\" style=\"margin-left: auto; margin-right: auto;\">\n <thead>\n  <tr>\n   <th style=\"text"| __truncated__
#>  - attr(*, "format")= chr "html"

str(sapply(species, function(x){
    starwars %>%
        dplyr::filter(species == x) %>%
        select(name, birth_year) %>%
        kable() %>%
        kable_styling(fixed_thead = TRUE, latex_options = c("striped", "scale_down")) %>%
        row_spec(0, bold = TRUE)
}, simplify = TRUE)[[1]])
#>  chr "<table class=\"table\" style=\"margin-left: auto; margin-right: auto;\">\n <thead>\n  <tr>\n   <th style=\"text"| __truncated__

reprex package (v0.3.0) 于 2020-07-09 创建 lapply returns 一个列表(具有 class c("kableExtra", "knitr_kable"),具有 attr(*, "format")= chr "html") 属性),而 sapply returns 一个向量attr(*, "names")= chr "Human".

字符