do.call() 和 apply() 中的 RMarkdown 格式化表以错误的顺序出现 [英] RMarkdown formattable tables within do.call() and apply() appearing in wrong order

查看:31
本文介绍了do.call() 和 apply() 中的 RMarkdown 格式化表以错误的顺序出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 RMarkdown 中打印一系列文本和可格式化表(即可格式化包).我希望输出显示为:

text 1可格式化表 1正文 2可格式化表 2正文 3可格式化表 3

我怎样才能达到想要的输出顺序?

解决方案

您可以使用返回文本的 paste 而不是打印它的 cat,并包括文本和div 中的表格:

do.call(div, lapply(1:3, function(i) {div(paste("Text", i, "到这里.\n"),show_plot(print(formattable(df, list(test1_score = color_bar("pink"))))))}))

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?

解决方案

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

这篇关于do.call() 和 apply() 中的 RMarkdown 格式化表以错误的顺序出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆