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

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

Return multiple gt tables in function

问题

以下是翻译好的内容:

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

library(gt)
df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))

return_multiple <- function(data) {
  tab1 <- df %>% gt()
  tab2 <- df %>% gt()
  
  return(tab1) # 只有第一个表格被打印
  return(tab2)

### 不起作用 ###
#  try <- list(tab1, tab2)
#  return(try) # 打印格式化代码
}

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.

```{r}
library(gt)
df &lt;- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))

return_multiple &lt;- function(data) {
  tab1 &lt;- df %&gt;% gt()
  tab2 &lt;- df %&gt;% gt()
  
  return(tab1) # only first table printed
  return(tab2)

### does not work ###
#  try &lt;- list(tab1, tab2)
#  return(try) # formatting code printed
}

return_multiple(df)
```

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

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

答案1

得分: 1

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

library(gt)
df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))

purrr::walk(list(df,df), ~.x %>%
                  gt() %>%
                  tab_caption("这里是标题") %>%
                  print())

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

英文:

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

---
output: html_document
---

```{r, results=&#39;asis&#39;}
library(gt)
df &lt;- data.frame(a=1:5, b=c(&quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;c&quot;, &quot;c&quot;))

purrr::walk(list(df,df), ~.x |&gt; 
              gt() |&gt; 
              tab_caption(&quot;Caption here&quot;) |&gt; 
              print())
```

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

答案2

得分: 1

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

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

return_multiple(df)
英文:

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

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

return_multiple(df)
```

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:

确定