我认为 R markdown 可以使用 for 循环生成文本部分,请参阅这篇文章。但是,我想知道是否有可能生成图形和表格。
所以我做了一个简单的例子。假设在 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)
其中
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
}
目标是在 5 个单独的部分下显示表格
formattable(df_list[[i]])
和图形 plot(df_list[[i]]$data)
。 (假设每个部分都有比我制作的示例更有意义的文本内容)类似于下面的 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")
}
```
只是另一个版本,带有
{.tabset}
和基于 Jlopes 答案的嵌套结构:
library(ggplot2)
for(i in 1:5){
cat("## Section ", i, "{.tabset}\n")
cat("\n\n")
df <- mtcars[sample(5),]
tb <- knitr::kable(df, caption = paste0("Table",i))
print(tb)
cat("\n\n")
for (j in 1:3) {
cat("### Section i=", i, " and j=", j, "\n")
g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
ggplot2::geom_point() +
ggplot2::labs(title = paste0("Figure ", i))
cat("\n")
cat("Text in i=", i, "and j=", j, "\n\n")
print(g1) # crashes header structure
cat("\n\n")
}
# print(tb) # layout here bad !?
}
有点奇怪,
\n\n
似乎是必要的,而最后的print(tb)
不起作用——至少我还没有让它发挥作用。