In this answer, @Yihui said that knitr
uses the global environment. This confused me--my experience had been that it doesn't. I never really use knit
though, I usually go straight to PDF.
In a little experiment, it seems that knit
does use the global environment (or whatever environment you specify using the envir
argument), but that knit2pdf
doesn't.
Minimal example: global_test.Rnw file
\documentclass{article}
\begin{document}
<<>>=
print(x)
@
\end{document}
R Script:
x <- "Hello World"
knit(input="global_test.Rnw")
# Works as expected, could now call tools::texi2pdf to generate pdf.
knit2pdf(input="global_test.Rnw")
# Doesn't
The latter generates PDF file that won't display and gives a warning:
running command '"C:\PROGRA~2\MIKTEX~1.9\miktex\bin\texi2dvi.exe" --quiet --pdf
"global.pdf" -I "C:/PROGRA~1/R/R-215~1.3/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-215~1.3/share/texmf/bibtex/bst"' had status 1
I tried passing an environment to knit2pdf
(envir = globalenv()
) hoping it would be ...
passed on, I just get an unused argument error.
Generally, I know that referencing the global environment is poor form, but is there a way to do it with knit2pdf
, or to pass an environment explicitly, or am I better off using brew
and sprintf
as in @Ramnath's answer to the same question above?
In my use case, I don't think tools::texi2pdf
is useful because I need to compile with XeLaTeX, which knit2pdf
handles effortlessly.
The problems with the examples in the question seem to have nothing to do with environments. Everything will compile correctly and without warnings if the output
argument is left off of knit2pdf
.
For reference, I was using knitr 1.1 on R 2.15.3 on Windows 7. I'll let Yihui know as it appears to be a bug in knit2pdf
(which calls tools::texi2pdf
, which doesn't accept an output file path).
UPDATE: The problem has been fixed in the development version of knitr
, available here.
It's also worth noting that the Compile PDF
button in RStudio does not use your current environment, so if you want to have access to global variables and you are using RStudio, make an explicit call to the appropriate knit
function rather than relying on the shortcut. In fact, it doesn't use knit2pdf
directly, rather it calls rmarkdown::render
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With