0

The following code is a very simplified MRE for an issue I'm experiencing. I'm trying to avoid R template packages, such as brew, and only use knit_expand() to achieve my goals. The issue is twofold:

  1. generated chunks don't get parsed (this is not happening in my real code, but happens in MRE)
  2. instead of LaTeX \includegraphics, knitr (or rmarkdown, or pandoc) generates RMarkdown syntax for inserting figures (![]).

In regard to the former, I have a feeling that it might be related to my incorrect use of get() or its argument. Your advice would be very much appreciated. The MRE follows ('.Rmd' document):

---
title: "MRE: a dynamic chunk issue"
author: "Aleksandr Blekh"
output:
  pdf_document:
    fig_caption: yes
    keep_tex: yes
    highlight: NULL
---

```{r, echo=FALSE, include=FALSE}
library(knitr)

opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE, message=FALSE, echo=FALSE, tidy=FALSE)
```

```{r Preparation, results='hide'}

g1 <- plot(cars)
g2 <- plot(iris$Sepal.Length)

myPlots <- list(g1, g2)

bcRefStr <- list("objType" = "fig",
                 "objs" = c("g1", "g2"),
                 "str" = "Plots \\ref{fig:g1} and \\ref{fig:g2}")
```

```{r DynamicChunk, include=FALSE}
chunkName <- "{{name}}"
chunkHeader <- paste0("```{r ", chunkName, ", ")
chunkOptions <- "include=TRUE, results='asis', fig.height=4, fig.width=4, fig.cap='{{name}}'"
chunkHeaderFull <- paste0(chunkHeader, chunkOptions, "}")
chunkBody <- "print(get('{{name}}'))"

latexFigEnvBegin <- "cat('\\\\begin{figure}')"
latexFigEnvEnd <- "cat('\\\\end{figure}')"
latexFigCenter <- "cat('\\\\centering')"

latexObjLabel <- paste0("cat('\\\\caption{\\\\ ", "{{name}}\\\\label{", bcRefStr$objType, ":{{name}}", "}}')")

chunkText <- c(chunkHeaderFull,
               latexFigEnvBegin, latexFigCenter,
               chunkBody,
               latexObjLabel, latexFigEnvEnd,
               "```", "\n")

figReportParts <- lapply(bcRefStr$objs, function (x) knit_expand(text = chunkText, name = x))
```

`r knit(text = unlist(figReportParts))`
Aleksandr Blekh
  • 2,462
  • 4
  • 32
  • 64
  • @Andrie: Thank you for editing my question. I was too concerned about the issue per se that overlooked improving the question's readability. – Aleksandr Blekh Nov 12 '14 at 10:11
  • Can you please make your example *minimal*? There is rather a lot of unnecessary creation of pretty graphs, for example. Simplify the plots. Then simplify and remove some of the latex formatting. This will allow the real problem to emerge. At the moment I am just staring at a wall of code, wondering what half of it does. – Andrie Nov 12 '14 at 10:13
  • @Andrie: I can definitely simplify plots. However, the LaTeX formatting is essential, as the whole idea of this dynamic chunk (template) is to automatically generate narrative's references and matching LaTeX code for a set of R objects (in this case, figures). I will be happy to clarify my LaTeX-related code, if it's too fuzzy. – Aleksandr Blekh Nov 12 '14 at 10:21
  • @Andrie: I've simplified plotting code. Sorry, but I'm not aware of how to disable displaying plots. – Aleksandr Blekh Nov 12 '14 at 10:36
  • 1
    I don't think your problem is fundamentally about knit chunks. Try running the code from R interactively, then just before the final chunk evaluate `invisible(sapply(figReportParts, cat)); lapply(figReportParts, function(p) knit(text=p))`. This is what gets knitted in the final chunk, but it contains errors. Fix that, and then the rest might fall in place. – Andrie Nov 12 '14 at 10:42
  • @Andrie: Thank you for the advice. I've already done similar debugging of the original version of this code, but will try again. – Aleksandr Blekh Nov 12 '14 at 10:45
  • Updated the question upon investigation and fixes. – Aleksandr Blekh Nov 12 '14 at 15:16
  • 1
    Prior to your edits, I thought I knew what you're asking. Now it's just one blur of text and code intermingled. I suggest you remove references to "current status" and "updates". Write the question so it's coherent to anybody reading the question with fresh eyes. Also, you don't really need all that latex to illustrate the nub of the issue. Try to make it *minimal*. PS. I have been messing about trying to understand what this code does, but not closer to an answer. – Andrie Nov 12 '14 at 16:29
  • To moderator, who deleted my comment in response to the one above: Please be consistent - either restore my comment, or, if you believe it's not applicable anymore after my update, then please delete the comment above, as it doesn't reflect the current state either. – Aleksandr Blekh Nov 14 '14 at 00:42
  • What does "MRE" mean? – Tripartio Jul 01 '18 at 19:45
  • 1
    @Tripartio **MRE** stands for _minimal reproducible example_. Please see details here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. There are similar answers elsewhere on Stack Exchange, but this should be enough to understand the concept and use it, regardless of programming language. – Aleksandr Blekh Jul 01 '18 at 21:24

1 Answers1

1

Finally, I've figured out what was causing the issue. The first part was easy. Due to suggested simplification, I've switched from ggplot2 to standard R graphics functions. The problem is that it appears that plot() doesn't return a value/object, so that's why NULLs has been seen in the output, instead of plots.

The second part was a bit more tricky, but an answer to a related question (https://stackoverflow.com/a/24087398/2872891) clarified the situation. Based on that information, I was able modify my MRE correspondingly and the resulting document appears with correct content (same applies to the generated LaTeX source, which seems to be ready for cross-referencing).

I'm thinking about converting this code into a more generic function for reuse across my project, if time will permit [shouldn't take long] (@Yihui, could this be useful for knitr project?). Thanks to everyone who took time to analyze, help or just read this question. I think that knitr's documentation should be more clear on issues, related to producing PDF documents from RMarkdown source. My solution for the MRE follows.

---
title: "MRE: a dynamic chunk issue"
author: "Aleksandr Blekh"
output:
  pdf_document:
    fig_caption: yes
    keep_tex: yes
    highlight: NULL
---

```{r, echo=FALSE, include=FALSE}
library(knitr)
library(ggplot2)

opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA, warning=FALSE, message=FALSE, echo=FALSE, tidy=FALSE)
```

```{r Preparation, results='hide'}
library(ggplot2)

g1 <- qplot(mpg, wt, data=mtcars)
g2 <- qplot(mpg, hp, data=mtcars)

myPlots <- list(g1, g2)

bcRefStr <- list("objType" = "fig",
                 "objs" = c("g1", "g2"),
                 "str" = "Plots \\ref{fig:g1} and \\ref{fig:g2}")
```

```{r DynamicChunk, include=FALSE}

latexObjLabel <- paste0("{{name}}\\\\label{", bcRefStr$objType, ":{{name}}", "}")

chunkName <- "{{name}}"
chunkHeader <- paste0("```{r ", chunkName, ", ")
chunkOptions <- paste0("include=TRUE, results='asis', fig.height=4, fig.width=4, fig.cap='", latexObjLabel, "'")
chunkHeaderFull <- paste0(chunkHeader, chunkOptions, "}")
chunkBody <- "print(get('{{name}}'))"

chunkText <- c(chunkHeaderFull,
               chunkBody,
               "```", "\n")

figReportParts <- lapply(bcRefStr$objs, function (x) knit_expand(text = chunkText, name = x))
```

`r knit(text = unlist(figReportParts))`
Community
  • 1
  • 1
Aleksandr Blekh
  • 2,462
  • 4
  • 32
  • 64