请参阅下面的reprex1
和reprex2
。 lapply
运行,但在{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)
})
答案 0 :(得分:0)
首先,我认为您可能希望在函数中添加一行内容,该行实际上对变量x进行了某些操作,例如过滤,否则您将返回两倍的相同输出。
sapply(x, f, simplify = FALSE, USE.NAMES = FALSE)
与lapply(x, f)
相同,因此您可以将下面的sapply
语句的输出与simplify = TRUE
与simplify = 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"
的字符向量。