do.call() 和 apply() 中的 RMarkdown 格式化表以错误的顺序出现
RMarkdown formattable tables within do.call() and apply() appearing in wrong order
我想在 RMarkdown 中打印一系列文本和 formattable tables(即 formattable 包)。我希望输出显示为:
text 1
formattable table 1
text 2
formattable table 2
text 3
formattable table 3
, I'm using the RMarkdown formattable example loop,它使用包装函数 do.call() 和 lapply() 而不是 for 循环。
这是该示例的精简版,它演示了我遇到的问题:
---
title: "formattable example loop"
output: html_document
---
```{r setup, echo = FALSE}
library(formattable)
library(htmltools)
df <- data.frame(
id = 1:10,
name = c("Bob", "Ashley", "James", "David", "Jenny",
"Hans", "Leo", "John", "Emily", "Lee"),
test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6)
)
show_plot <- function(plot_object) {
div(style="margin:auto;text-align:center", plot_object)
}
```
```{r, results = 'asis', echo = FALSE}
### This is where I'm having the problem
do.call(div, lapply(1:3, function(i) {
cat("Text", i, "goes here. \n")
show_plot(print(formattable(df, list(
test1_score = color_bar("pink")
))))
}))
```
由于该函数打印 "Text i goes here",然后打印格式 table table,我认为生成的文档会如上所示(text1 和 table1,然后text2 和 table 2,然后是 text3 和 table 3).
但是,它的顺序是 text1 和 text2 和 text3,然后是 table1 和 table2 和 table3,就像这样:
怎样才能达到想要的输出顺序?
您可以使用 paste
其中 returns 文本而不是 cat
打印它,并将文本和 table 包含在 div
中:
do.call(div, lapply(1:3, function(i) {
div(paste("Text", i, "goes here. \n"),
show_plot(print(formattable(df, list(test1_score = color_bar("pink"))))))
}))
我想在 RMarkdown 中打印一系列文本和 formattable tables(即 formattable 包)。我希望输出显示为:
text 1
formattable table 1
text 2
formattable table 2
text 3
formattable table 3
这是该示例的精简版,它演示了我遇到的问题:
---
title: "formattable example loop"
output: html_document
---
```{r setup, echo = FALSE}
library(formattable)
library(htmltools)
df <- data.frame(
id = 1:10,
name = c("Bob", "Ashley", "James", "David", "Jenny",
"Hans", "Leo", "John", "Emily", "Lee"),
test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6)
)
show_plot <- function(plot_object) {
div(style="margin:auto;text-align:center", plot_object)
}
```
```{r, results = 'asis', echo = FALSE}
### This is where I'm having the problem
do.call(div, lapply(1:3, function(i) {
cat("Text", i, "goes here. \n")
show_plot(print(formattable(df, list(
test1_score = color_bar("pink")
))))
}))
```
由于该函数打印 "Text i goes here",然后打印格式 table table,我认为生成的文档会如上所示(text1 和 table1,然后text2 和 table 2,然后是 text3 和 table 3).
但是,它的顺序是 text1 和 text2 和 text3,然后是 table1 和 table2 和 table3,就像这样:
怎样才能达到想要的输出顺序?
您可以使用 paste
其中 returns 文本而不是 cat
打印它,并将文本和 table 包含在 div
中:
do.call(div, lapply(1:3, function(i) {
div(paste("Text", i, "goes here. \n"),
show_plot(print(formattable(df, list(test1_score = color_bar("pink"))))))
}))