RMarkdown formattable tables within do.call() and apply() appearing in wrong order

China☆狼群 提交于 2021-02-08 04:28:25

问题


I'd like to print a series of texts and formattable tables (i.e. the formattable package) in RMarkdown. I would want the output to appear as:

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, I'm using the RMarkdown formattable example loop, which uses a wrapper function, do.call() and lapply() instead of a for loop.

Here's a slimmed-down version of that example that demonstrates the issue I'm having:

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

))))

}))
```

Since the function prints "Text i goes here", then prints the formattable table, I thought the resulting document would appear as above (text1 and table1, then text2 and table 2, then text3 and table 3).

However, it's in the order text1 and text2 and text3, then table1 and table2 and table3, like so:

How can I achieve the desired order of output?


回答1:


You can use paste which returns text instead of cat which prints it, and include the text and table within a 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"))))))
}))


来源:https://stackoverflow.com/questions/41050525/rmarkdown-formattable-tables-within-do-call-and-apply-appearing-in-wrong-ord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!