R markdown:使用for循环生成文本并显示图形/表格

2024-02-09

我认为 R markdown 可以使用 for 循环生成文本部分,请参阅这个帖子 https://stackoverflow.com/questions/36674824/use-loop-to-generate-section-of-text-in-rmarkdown。但是,我想知道是否也有可能生成图形和表格。

所以我做了一个简单的例子。假设在 R markdown 中,我想要有 markdown 语言并显示下面的表格和图。

这将返回一个表格和一个图。

df<- data.frame(
  name = LETTERS[1:12],
  data = runif(n = 12))
new_df<-some_function(df,1)
formattable(new_df)
plot(new_df$data)

where some_function是一个简单的函数,执行以下操作

some_function<-function(df,loc){
  df$data<-df$data+loc
  return(df)
}

所以我希望重复 5 次,这意味着生成以下选择 5 次。

这将返回一个表格和一个图。

(图:假装那里有一个人影) (桌子:假装那里显示了一张桌子)

我应该如何使用一些模板编写代码来显示表格和图形?生成列表的代码new_df在下面。

df_list=list()
for (i in 1:5){
  new_df<-some_function(df,i)
  df_list[[i]]<-new_df
}

目标是显示表格formattable(df_list[[i]])和数字plot(df_list[[i]]$data)在 5 个单独的部分下。 (假设每个部分都有比我制作的示例更有意义的文本内容)类似于下面的 screktch。

template <- "## This will return a table and a figure.
Table is: formattable(df_list[[i]])
Figure is: plot(df_list[[i]]$data)

"

for (i in 1:5) {
  current <- df_list[[i]]
  cat(sprintf(template, current,current$data))
}

有可能实现这个目标吗?任何想法或想法都非常受欢迎。


您可以使用result = 'asis'在 - 的里面r chunk并使用cat()创建部分。

---
title: "R Notebook"
output:
  html_document
---

## Example

```{r, results='asis'}
require(ggplot2)
for(i in 1:5){
  cat("### Section ", i, "\n")
  
  df <- mtcars[sample(5),]
  tb <- knitr::kable(df, caption = paste0("Table",i))
  g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
    ggplot2::geom_point() +
    ggplot2::labs(title = paste0("Figure ", i))
  cat("\n")
  print(g1)
  print(tb)
  cat("\n")
}
```
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R markdown:使用for循环生成文本并显示图形/表格 的相关文章

随机推荐