I think the R markdown can generate sections of text using for loop, see this post. However, I wonder if there is any possibility to generate figures and tables as well.
So I made a simple example. Assume in R markdown, I want to have the markdown language and display the table and plot below.
This will return a table and a plot.
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
is a simple function that does the following
some_function<-function(df,loc){
df$data<-df$data+loc
return(df)
}
So I hope to get this repeated 5 times, which means generating the below selection 5 times.
This will return a table and a plot.
(figure: pretend there displayed a figure) (table: pretend there displayed a table)
How should I write the code using some template to display the tables and figures? The code for generating a list of new_df
is below.
df_list=list()
for (i in 1:5){
new_df<-some_function(df,i)
df_list[[i]]<-new_df
}
The goal is to display the tables formattable(df_list[[i]])
and figures plot(df_list[[i]]$data)
under the 5 separate sections. (Assume each section will have more meaningful text content than the example I made) Something like this screktch below.
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))
}
Is that possible to accomplish this? Any thoughts or ideas are very welcome.