英文:
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))时的输出:
英文:
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 <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
return_multiple <- function(data) {
tab1 <- df %>% gt()
tab2 <- df %>% gt()
return(tab1) # only first table printed
return(tab2)
### does not work ###
# try <- list(tab1, tab2)
# return(try) # formatting code printed
}
return_multiple(df)
```
This is the output when I return the list (return(try)):
答案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())
英文:
You could use purrr::walk
for this, e.g.
---
output: html_document
---
```{r, results='asis'}
library(gt)
df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
purrr::walk(list(df,df), ~.x |>
gt() |>
tab_caption("Caption here") |>
print())
```
答案2
得分: 1
只需将 results='asis'
添加到您的原始方法中:
library(gt)
df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
return_multiple <- function(data) list(gt(data), gt(data))
return_multiple(df)
英文:
Just add results='asis'
to your original approach:
```{r echo=F, results='asis'}
library(gt)
df <- data.frame(a=1:5, b=c("a", "c", "a", "c", "c"))
return_multiple <- function(data) list(gt(data), gt(data))
return_multiple(df)
```
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论