我想在RMarkdown中打印一系列文本和格式表(即格式表包)。我希望输出显示为:
text 1
formattable table 1
text 2
formattable table 2
text 3
formattable table 3
Since formattable tables don't appear when using a for loop,我正在使用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”,然后打印formattable表,我认为结果文档将如上所示(text1和table1,然后是text2和table2,然后是text3和table3)。
然而,它的顺序是text1和text2以及text3,然后是table1和table2以及table3,如下所示:
如何实现所需的输出顺序?
答案 0 :(得分:4)
您可以使用paste
返回文本而不是cat
来打印它,并将文本和表格包含在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"))))))
}))