Rmarkdown乳胶输出:sapply问题

时间:2020-07-09 16:20:37

标签: r r-markdown kable

请参阅下面的reprex1reprex2lapply运行,但在{tex}中,在{tex}的第87行的开头添加了sapply,将其中断。

想法?

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

1 个答案:

答案 0 :(得分:0)

首先,我认为您可能希望在函数中添加一行内容,该行实际上对变量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返回一个列表(类别为c("kableExtra", "knitr_kable"),属性为attr(*, "format")= chr "html")),而sapply返回一个带有attr(*, "names")= chr "Human"的字符向量。