2

First of all I am new to R programming. Also I found some topics that are very close to what I cannot solve but don't really help me in the end.

I have inherited a report which pastes some graphs in a folder in the form of .png images which are then knitted in a word report.

I have managed to automate the someScriptIn.R part and it is able to analyse a .csv file to find out how many data sets it has to analyse and set the titles,dates,etc right. It produces the images just fine.

You have to know that what I want to do is to have a dynamically changing report in terms of number of data sets, titles etc. So it will not be let's say 3 sets of images every time. it may be 1 it may be 10. This will depend on the user. Also the Series.title is a variable created in someScriptIn.R as well as Series.quarter.

The issue starts when I try to use knitr with an .rmd file that looks like the below code.

Code:

---
output: word_document
---


```{r, echo=FALSE, results='hide'}
# source(".../someScriptIn.R") # this will produce the graphs
```
`r Series.title[1]` `r Series.quarter` Quarters Forecast # here Series.title[1] is Group 1
  ![](graph1-1.png)
  ![](graph2-1.png)
  ![](graph3-1.png)
`r Series.title[1]` `r Series.quarter` Quarters Forecast # here Series.title[2] is Group 2
  ![](graph1-2.png)
  ![](graph2-2.png)
  ![](graph3-2.png)
`r Series.title[1]` `r Series.quarter` Quarters Forecast # here Series.title[3] is Group 3
  ![](graph1-3.png)
  ![](graph2-3.png)
  ![](graph3-3.png)

The question is how to go through this with a for loop having in mind that the graphs are already created images in a folder? Is this solution able to solve my problem and what will the implementation be?

Community
  • 1
  • 1

2 Answers2

1

Use an "asis" chunk:

---
output: 
  word_document
---


```{r, results="asis", echo=FALSE}
cat("First part of report\n\n")
cat(paste0("![bb](a",1:3,".png)", sep="", collapse="\n\n"))
```

Simplified assumption that files are a1.png, a2.png, a3.png.

Dieter Menne
  • 10,076
  • 44
  • 67
0

You can do it using 2 for loops and the sprintf function:

```{r, results='asis', echo=FALSE}
Series.title <- c("Group 1", "Group 2", "Group 3")
Series.quarter <- "SQ?"

for (i in 1:3) {
    cat(sprintf("%s %s Quarters Forecast \n\n", Series.title[i], Series.quarter))
    for (j in 1:3) {
        cat(sprintf("![](graph%i-%i.png) \n", j, i))
    }
}
```

Output from for loop:

Group 1 SQ? Quarters Forecast 

![](graph1-1.png) 
![](graph2-1.png) 
![](graph3-1.png) 
Group 2 SQ? Quarters Forecast 

![](graph1-2.png) 
![](graph2-2.png) 
![](graph3-2.png) 
Group 3 SQ? Quarters Forecast 

![](graph1-3.png) 
![](graph2-3.png) 
![](graph3-3.png) 
JohannesNE
  • 1,343
  • 9
  • 14