Dynamic LaTeX references in R comment with knitr - r

I had ask a similar question to this with respect to Sweave (
Dynamic references to figures in a R comment within Sweave document
) and would like to see if anyone as a similar answer when using knitr.
The goal is to have the following code chunk
<<"example", fig.cap = "some figure", highlight = FALSE>>=
# the following code generated Figure \ref{fig:example}
plot(1:10, 1:10)
#
have be displayed in the resulting .pdf as
# the following code generated Figure 1.1
plot(1:10, 1:10)
So far I have found that by setting highlight = FALSE the R code is placed into a verbatim environment in the resulting .tex file. If the environment could be alltt instead of verbatim then we'd have the desired output. Is it possible to have the non-highlighted code chunks be placed in alltt environments via a knitr option?

I have added an example 072-latex-reference.Rnw in the knitr-examples repository. The basic idea is to restore the escaped \ref{} (which should have been \textbackslash{}ref\{\} in the default output).

Related

Change option settings with knit:pagedown::chrome_print in Rmarkdown YAML

I have created a large R Markdown document with many child docs using RStudio to produce output in both HTML and PDF.
I added this simple line to the YAML parameters of the document and it does exactly what I need. The entire doc is rendered and saved as both html and pdf output. Formatting of complex tables is preserved nicely.
knit: pagedown::chrome_print
BUT - the pdf is oversized. It simply needs to be scaled to 0.8 to be really useable. chrome_print documentation says that scale can be adjusted within the chrome_print command. I've tried this:
knit: pagedown::chrome_print(scale = 0.8)
which produces an Execution Halted error. I have tested other ways to pass parameters through the render to chrome_print, but none work.
The question is simple: Is there a way to pass parameters into the knit: pagedown::chrome_print operation?
After much experimentation, I find there is currently no way to adjust any pdf options from within R markdown YAML using knit: pagedown::chrome_print.
The workaround I've found is to use the code chunk below to render the Rmarkdown. It saves to both html and pdf formats and allows the user to assign filenames. Note that scaling does not adjust pagination nicely without CSS reset as shown. This works great, and allows full use of rmarkdown parameters and all chrome_print options.
fname = "OutputFilename"
pagedown::chrome_print(
rmarkdown::render(
input = "input.Rmd",
output_file = paste0(fname, ".html"),
output = paste0(fname, ".pdf"),
options = list(scale = 0.7, preferCSSPageSize = FALSE))

knitr: why does nothing appear in the "environment" panel when I compile my .Rnw file

I am new to knitr. I have made a practise .Rnw file with some very simple commands. For example:
\documentclass[12pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks = true, %Colours links instead of ugly boxes
urlcolor = blue, %Colour for external hyperlinks
linkcolor = blue, %Colour of internal links
citecolor = blue %Colour of citations
}
\usepackage{caption}
\captionsetup[figure]{labelfont=bf, labelsep=period}
\captionsetup[table]{labelfont=bf, labelsep=period}
\setlength{\parindent}{0pt}
\title{My very first LaTeX/knitr document!}
\date{April 2019}
\begin{document}
\maketitle
\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup
\newpage
\section{Basics}
\subsection{Using no options}
First, let's try and a show a chunk of code along with a plot and print() message.
<<first-chunk>>=
# Make a simple dataframe:
setwd("/home/user/Documents/testing-area/knitr/")
df <- data.frame(A = c(1,2,3), B = c("A", "B", "C"))
plot(df$A,df$B)
print("hello")
#
When I click on "Compile PDF", I get a PDF with all the code (as I expect, since I didn't use echo = FALSE), as well as the plot itself and the print statement.
My question is: why do I not see "df" in Rstudio, in my "Environment" panel, like you "usually" when simply running a .R script in Rstudio? Clearly, R is running the code in the code chunk and producing the PDF. So why is there nothing in the Environment. If I run the R code in the .Rnw file "manually", I do get "df" in the Environment.
Am I missing something? I know it doesn't really matter, since my code still technically runs, but I find unituitive that Rstudio doesn't show anything in the Environment. Is there a reason for this?
Thanks.
The usual way to knit an Rnw file by clicking on Compile PDF in RStudio does it in an independent R process. Your document won't see local variables in your workspace, and variables created in it won't last beyond the processing.
There are ways to change this. If you explicitly knit the process in the R console, e.g.
knitr::knit2pdf("file.Rnw")
then it will be able to see the variables in your local workspace, but changes it makes won't be saved. To also save results, use
knitr::knit2pdf("file.Rnw", envir = globalenv())
which says to evaluate the code in the global environment (i.e. your workspace).

run an R Markdown (check.Rmd ) and an R knitr (test.Rnw ) file together

I have the following problem; There are 2 big documents, one written in R Markdown (check.Rmd ) and the other in R knitr (test.Rnw ). In the first doc we have a code like the following:
\section{Organisations Test}
\textbf{Running Organisations Checks}
<<CreateOrganisations, echo=FALSE, progress=TRUE, warning=FALSE, eval=TRUE>>=
source("OrganisationsTest.R")
OrganisationsTest(current_schema,server,user,pass)
#
and in the other as follows:
2. check the downwards shock
```{r chunk_Int_Sh_p2, echo=FALSE}
unique(param.int.shock.tab[SHOCKTYPE=="SHOCK_DOWN"&PERIODEND<21|PERIODEND==90, list( Maturity=PERIODEND, Shock_value=100*SHOCKVALUE)])
```
Now the question: how can I combine both so that I have just one script which runs and compile both one after each other. Just for clarification, I mean without any changes in both documents how can I have just one script which applyes to the first doc knit PDF to create pdf and to the other one CompilePDF ?
I suppose in Linux one can write a shell script but what a bout using RStudio in windowes?
I am really grateful for every hint I am a little bit helpless!
Addendum: In principle it is as follows: we have 2 files if you would compile a knitr file you would use bottom in RStudio, and for a Markdown file one may use bottom in RStudio, BUT we want to put both together and klick on one bottom. How is it possible?
The RStudio buttons "Compile PDF" (for RNW documents) and "Knit PDF" (for RMD documents) are convenient, but in cases like this one it is important to understand what they do in order to reproduce the same or similar behavior.
Summing the question up, it asks for a way to convert two files (a RMD and a RNW document) to PDF, preferably using a button like the two buttons mentioned above.
Unfortunately, (up to my knowledge) it is not possible to add any user-defined buttons to the RStudio GUI. But it is straightforward to write an R script that compiles both documents.
In the following I assume two files:
first.Rmd:
This is a RMD file.
```{r, echo=FALSE}
plot(1)
```
second.Rnw:
\documentclass{article}
\begin{document}
This is a RNW file.
<<>>=
plot(1)
#
\end{document}
To compile first.Rmd to PDF, we need the following (see How to convert R Markdown to PDF?):
library(knitr)
library(rmarkdown)
knit(input = "first.Rmd")
render(input = "first.md", output_format = "pdf_document")
The knit call generates first.md from first.Rmd, execting the R code in the chunks. render converts the resulting markdown file to PDF. [Note the addendum at the bottom!]
To compile first.Rnw to PDF, we can simply use knit2pdf:
knit2pdf("second.Rnw")
Copying both snippets into one R script and clicking "Source" is as close as possible to a "one-button-solution".
However, note that the snippets do something very similar to the "Compile / knit PDF" button, but it is not identical. The "Compile" buttons start a new R session while the solution above uses the current session.
Before executing the snippets make sure to use the correct working directory.
Both knit and knit2pdf by default use envir = parent.frame(). That means R code in chunks is executed in the calling enironment (see What is the difference between parent.frame() and parent.env() in R). This can be a useful feature, for example to "pass" variables to chunks, but it is important to know about it. Otherwise a document might compile just fine in one session (where certain variables exist in the calling environment) but cannot be compiled in another session (that is missing these variables). Therefore, this feature is a little bit dangerous in terms of reproducibility. As a solution, envir = new.env(parent = as.environment(2)) could be used; see knitr inherits variables from a user's environment, even with envir = new.env() for more details on that topic.
I just realized to following about render:
If the input requires knitting then knit is called prior to pandoc.
(Source: ?render)
Therefore, knit(input = "first.Rmd"); render(input = "first.md", output_format = "pdf_document") can be simplified to render(input = "first.Rmd", output_format = "pdf_document"). The envir issues of knit from above apply to render as well.

global comment option for R markdown in knitr

To change the leading characters for the output a knitr chunk in .Rmd has a comment option, like
```{r comment = ""}
1:100
```
Is there a way to set this globally, not separately for every chunk?
opts_knit$set(comment = "")
does not work and I cannot find it anywhere in the documentation.
Use opts_chunk$set() because that is a chunk option; opts_knit is for package options (sorry about the similar names which apparently confused you). See http://yihui.name/knitr/options

Getting Sweave code chunks inside some framed box?

I would like to make an R code chunk (in Sweave) printed inside a framed box in the resulting pdf.
Is there an easy solution for doing that?
The short answer is that yes, there is an easy way. Just add the following lines, or something like them to the preamble of your Sweave document:
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
This works because the appearance of code (and output) chunks is controlled by the definition of the Sinput and Soutput environments. These are both Verbatim environments as provided by the LaTeX package fancyvrb. (Click here for a 73 page pdf describing the numerous options that fancyvrb provides).
A quick look in the file Sweave.sty reveals the default definition of those two environments:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}
To change those definitions, just add \DefineVerbatimEnvironment statements of your own devising either: (a) at the end of the Sweave.sty file; or (b) at the start of your *.Snw document.
Finally, here's an example to show what this looks like in practice:
\documentclass[a4paper]{article}
\usepackage{Sweave}
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
\title{Sweave with boxes}
\begin{document}
\maketitle
<<echo=FALSE>>=
options(width=60)
#
Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.
<<>>=
print(rnorm(99))
#
\end{document}
knitr, a successor of Sweave, by default outputs all echoed R code in boxes, and also formats it to the margins. Other nice features include syntax coloring and PGF integration.
Sweave code of average complexity needs only minor if any adaptions to run with knitr.

Resources