【问题标题】:Rmarkdown latex output: issue with sapplyRmarkdown 乳胶输出:sapply 的问题
【发布时间】:2020-07-09 16:20:37
【问题描述】:

请参阅下面的 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)
})

【问题讨论】:

    标签: r r-markdown kable


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多