66069

knitr templating - Dynamic chunks issue

Question:

The following code is a very simplified <em>MRE</em> 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 <strong>issue</strong> is twofold:

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

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 <strong>MRE</strong> 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))`

Answer1:

Finally, I've figured out what was causing the <strong>issue</strong>. The <em>first part</em> 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 <em>second part</em> was a bit more tricky, but an answer to a related question (<a href="https://stackoverflow.com/a/24087398/2872891" rel="nofollow">https://stackoverflow.com/a/24087398/2872891</a>) 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 <strong>solution</strong> 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))`

Recommend

  • P-values significance not showed in stargazer html regression table
  • After creating an executable ShinyApp when Rendering Rmarkdown Stops in R
  • Can't generate plotly interactive plots in Rmarkdown report
  • web2py : downloading zip file created by cStringIO text strings in controller
  • Oracle SELECT statement slow
  • Testing point with in/out of a vector shapefile
  • opts_current: how does it work in knitr?
  • Remove unmatched HTML tags in a string
  • FLOT: Order the y axis by minimum date
  • Converting Fortran IV to 77
  • How to get minimal absolute path from relative path without any permission checks?
  • Specify datetime format for WCF Data Service
  • How can I export a gbm model in R?
  • Controlling volume of running applications in Mac OS X via Objective-C
  • Entity Framework Core 2.0 add-migration not generating anything
  • Make background for table rows extend past the bounds of the table
  • dismiss Progress Dialog in another Activity … Android
  • How to synchronize two scrollview in Android?
  • How do you create a Fuseki SPARQL server using the Apache Jena Java API?
  • pandas computation in each group
  • How to estimate the Kalman Filter with 'KFAS' R package, with an AR(1) transition equation
  • Plotting line graph with factors in R
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • Is playing sound in Javascript performance heavy?
  • C: Incompatible pointer type initializing
  • Custom Tabgroup Appcelerator
  • $wpdb not working in file of WordPress plugin
  • NHibernate Validation Localization with S#arp Architecture
  • How can I send an e-mail from a vbs script
  • Insert into database using onclick function
  • Accessing IRQ description array within a module and displaying action names
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Knitr HTML Loop - Some HTML output, some R output
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Arrays break string types in Julia
  • File upload with ng-file-upload throwing error
  • Getting Messege Twice Using IMvxMessenger
  • Unable to use reactive element in my shiny app