Debugging knitting from rmarkdown using ProjectTemplate
This post summarises some general and specific points about debugging an rmarkdown file.
General Strategy
In general, users realise they have a problem when something that is working when in manual mode, does not work when they press the knit button in RStudio.
A common cause of this problem is that objects in current workspace are not in the knitr workspace.
it is common to get errors like:
Line ... Error in eval (expr, envir, enclos) : object 'foo' not found
where foo is an object like a data frame or something else you are working with.
In some cases, there will be an obvious error in your code that you can quickly fix up.
After that, a first general step in debugging the problem is to clear the workspace (e.g., by pressing the broom button in rstudio, or typing rm(list=ls()) into the console). Then run each code chunk consecutively starting from the first one in the knitr file. There are shortcut keys in RStudio for running both the current and next code chunk. This can speed up the process. If you get an error, then fix that code.
Sometimes you can get issues, if you issue some commands that are not meant to appear in the knitr documents. In partiuclar, requesting help for a function can cause knitr to hang. So remove any instances of that.
If everything is working after you have cleared the workspace and run all the code manually, its possible that the relationship between the rmarkdown file other files is broken. So, you need to check that the working directory in manual mode is the same as when you run knitr. You can get the current manual-mode working directory by typing getwd(). By default, knitr will use the folder that it is in as the working directory. However, if you are using my modified ProjectTemplate structure, I find it tider to keep the rmarkdown files in a subdirectory called reports. If you do this, then you need to include a command in the first code chunk to tell knitr to treat the working directory as one level up.
Thus, the first code chunk should have the following code inside:
library(knitr) opts_knit$set(root.dir = normalizePath('../')) # required when rmd is in subdirectory
Alternatively, you can just move the rmd file up one level manually and not include the above chunk.
Other assorted errors
Need a later version of rmarkdown: Sometimes RStudio will indicate that it needs a later version of rmarkdown. I've seen in some cases that RStudio's script for this can fail. if so, just install the rmarkdown package with install.packages("rmarkdown")
Can't knit to PDF: In general, you need to install a tex distribution. This is free and fairly large download: https://www.latex-project.org/get/









