简体   繁体   中英

R markdown: Use for loop to generate text and display figure/table

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.

You can use result = 'asis' inside the r chunk and use cat() to create the sections.

---
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")
}
```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM