在函数中返回多个gt表格。

huangapple go评论98阅读模式
英文:

Return multiple gt tables in function

问题

以下是翻译好的内容:

有没有办法在R Markdown中从用户编写的函数中返回多个gt表格?通常情况下,我会将表格组合成一个列表并输出它们。但是当我这样做时,HTML文档会显示一些格式化代码,而不是表格。

  1. library(gt)
  2. df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
  3. return_multiple <- function(data) {
  4. tab1 <- df %>% gt()
  5. tab2 <- df %>% gt()
  6. return(tab1) # 只有第一个表格被打印
  7. return(tab2)
  8. ### 不起作用 ###
  9. # try <- list(tab1, tab2)
  10. # return(try) # 打印格式化代码
  11. }
  12. return_multiple(df)

这是当我返回列表(return(try))时的输出:

在函数中返回多个gt表格。

英文:

Is there a way to return multiple gt tables from a user written function within R markdown? Typically, I would combine tables in a list and output them. However when I do so, the html document displays some formatting code instead of the tables.

  1. ```{r}
  2. library(gt)
  3. df &lt;- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))
  4. return_multiple &lt;- function(data) {
  5. tab1 &lt;- df %&gt;% gt()
  6. tab2 &lt;- df %&gt;% gt()
  7. return(tab1) # only first table printed
  8. return(tab2)
  9. ### does not work ###
  10. # try &lt;- list(tab1, tab2)
  11. # return(try) # formatting code printed
  12. }
  13. return_multiple(df)
  14. ```

This is the output when I return the list (return(try)):

在函数中返回多个gt表格。

答案1

得分: 1

你可以使用purrr::walk来实现这个,例如:

  1. library(gt)
  2. df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
  3. purrr::walk(list(df,df), ~.x %>%
  4. gt() %>%
  5. tab_caption("这里是标题") %>%
  6. print())

在函数中返回多个gt表格。

英文:

You could use purrr::walk for this, e.g.

  1. ---
  2. output: html_document
  3. ---
  4. ```{r, results=&#39;asis&#39;}
  5. library(gt)
  6. df &lt;- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))
  7. purrr::walk(list(df,df), ~.x |&gt;
  8. gt() |&gt;
  9. tab_caption(&quot;Caption here&quot;) |&gt;
  10. print())
  11. ```

在函数中返回多个gt表格。

答案2

得分: 1

只需将 results=&#39;asis&#39; 添加到您的原始方法中:

  1. library(gt)
  2. df <- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))
  3. return_multiple <- function(data) list(gt(data), gt(data))
  4. return_multiple(df)
英文:

Just add results=&#39;asis&#39; to your original approach:

  1. ```{r echo=F, results=&#39;asis&#39;}
  2. library(gt)
  3. df &lt;- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))
  4. return_multiple &lt;- function(data) list(gt(data), gt(data))
  5. return_multiple(df)
  6. ```

huangapple
  • 本文由 发表于 2023年4月13日 21:30:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定