【问题标题】:Reproducible ad-hoc report in R with knitr使用 knitr 在 R 中可重现的临时报告
【发布时间】:2015-10-06 12:51:01
【问题描述】:

首先,我是 R 编程的新手。我还发现了一些非常接近我无法解决但最终并没有真​​正帮助我的主题。

我继承了一份报告,该报告以 .png 图像的形式将一些图形粘贴到文件夹中,然后将这些图形编入文字报告中。

我已经设法自动化了 someScriptIn.R 部分,它能够分析 .csv 文件以找出它需要分析的数据集数量,并正确设置标题、日期等。它产生的图像就好了。

您必须知道,我想要做的是根据数据集、标题等的数量动态变化的报告。所以不会每次都说 3 组图像。它可能是 1 可能是 10。这取决于用户。 Series.title 也是在 someScriptIn.R 和 Series.quarter 中创建的变量。

当我尝试将 knitr 与类似于以下代码的 .rmd 文件一起使用时,问题就开始了。

代码:

---
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)

问题是如何通过 for 循环完成此操作,同时记住图形已经在文件夹中创建图像? this 解决方案能解决我的问题吗?具体实现是什么?

【问题讨论】:

    标签: r report knitr


    【解决方案1】:

    使用“asis”块:

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

    文件为a1.png, a2.png, a3.png的简化假设。

    【讨论】:

      【解决方案2】:

      您可以使用 2 个 for 循环和 sprintf 函数来做到这一点:

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

      for 循环的输出:

      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) 
      

      【讨论】:

      • 感谢聪明的解决方案,这正是我想要做的:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2013-02-14
      相关资源
      最近更新 更多