I have been unable to get external code chunks to work in knitr from a LaTeX (*.Rtex) document.
foo.R contains:
## #knitr foo
#
tx <- seq(0,2*pi,length.out=100)
ty <- cos(tx*3.0)
plot(tx,ty,pch=20,col='blue')
seq(3)
The test1.Rtex document contains:
%% read_chunk('Code/foo.R')
%
%%
%% begin.rcode foo, echo=TRUE, tidy=TRUE, eval=TRUE
%% end.rcode
knit('test1.Rtex') yields:
chunk "foo" is empty or set not to be evaluated
I have a copy of the knitr git repository. Modifying this code with cat(sprint()) statements there is no evidence of read_chunk() being used in LaTeX code.
Related
I am writing an R Markdown document using the Python engine of {reticulate}. I am quite happy with how it works.
The only thing is, I cannot use r as a Python object name that I'm going to use in multiple chunks.
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
I understand r is a good name when we use R objects from within a Python chunk. Since I know I am not going to do that in my project, I would like to use r as a name for my Python object.
Is there any way to change the name, r, for the R object created by reticulate? Or, to tell reticulate not to create r object?
I am aware of the two straightforward workarounds
Don't use r for Python objects.
Write everything in one big chunk and not share r between Python chunks.
but I'd like to have more freedom.
The object name r is special since it is used to communicate between R and python. The same holds for py in R:
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
Avoiding the use of r as an opject name is therefore the only good possibility I can see.
Still working on the details but I think setting source and output knit hooks may help. My dirty first try looks like this:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```
I have produced a dynamic document using knitr. The document makes
extensive use of the package's knit_expand() function for
templates. This is illustrated by the MWE (based on Yihui Xie's own
example for the function).
Main document knit-expand-MWE.Rnw
\documentclass{article}
\title{How to extract code when using\\
knit\_expand() for templates?}%
\author{Knitr User}
\begin{document}
\maketitle
\tableofcontents
\newpage
\section{Write one row of data}
Only the first two sections are evaluated.
<<run-all, include=FALSE>>=
library(knitr)
src = NULL
for (i in 1:3) src = c(src, knit_expand('template.Rnw'))
#
\Sexpr{paste(knit(text = src), collapse = '\n')}
\end{document}
Template template.Rnw called by main document
\subsection{Now i is {{i}}}
This chunk is {{if (i > 2) 'not '}}evaluated.
<<row-{{i}}, eval={{i <= 2}}>>=
# row number {{i}}
iris[{{i}}, ]
#
I now need to extract the corresponding R code. Running purl("knit-expand-MWE.Rnw") outputs knit-expand-MWE.R, which includes the code in the chunk with a reference to the template:
## ----run-all, include=FALSE----------------------------------------------
library(knitr)
src = NULL
for (i in 1:3) src = c(src, knit_expand('template.Rnw'))
What I would like instead is the corresponding "expanded" code (for the benefit of colleagues who do not use knitr), for example:
## ----row-1, eval=TRUE----------------------------------------------
## row number 1
iris[1, ]
## ----row-2, eval=TRUE----------------------------------------------
## row number 2
iris[2, ]
## ----row-3, eval=FALSE----------------------------------------------
## row number 3
iris[3, ]
How can I achieve this?
You can run purl() on src, e. g.
purl(text = src, output = 'knit-expand.R')
I have been using knitr for a while to generate some quite complex PDFs. On one of my machines knit2pdf started to cause me issues, and I cannot figure out why. knit2pdf continues to work on my other machines.
My typical setup is:
test.Rnw
\documentclass{article}
\begin{document}
This is a test
\end{document}
R Command
knit2pdf(input = "latex/test.Rnw", output = 'latex/knit2pdf', clean = TRUE)
however, I receive the following error message:
knit2pdf(input = "latex/test2.Rnw", output = 'latex/knit2pdf', clean = TRUE)
processing file: latex/test2.Rnw
|.................................................................|
100% ordinary text without R code
output file: latex/knit2pdf
[1] "latex/knit2pdf.pdf" Warning message: running command
'"C:\PROGRA~1\MIKTEX~1.9\miktex\bin\x64\texify.exe" --quiet --pdf
"knit2pdf" --max-iterations=20 -I
"C:/PROGRA~1/R/R-33~1.2/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-33~1.2/share/texmf/bibtex/bst"' had status 1
and the contents of knit2pdf.pdf is:
article[]graphicx[]color fgcolorrgb0.345, 0.345, 0.345
[1][rgb]0.686,0.059,0.5691[1][rgb]0.192,0.494,0.81[1][rgb]0.678,0.584,0.6861[1][rgb]0,0,01[1][rgb]0.345,0.345,0.3451[1][rgb]0.1framed
kframetotalleftmargin# setminipage #end#of#kframe shadecolorrgb.97,
.97, .97 messagecolorrgb0, 0, 0 warningcolorrgb1, 0, 1 errorcolorrgb1,
0, 0 knitrout alltt upquote.styupquote document This is a test
I have managed to get the output I require (using the example from How to create multiple PDFs with different content from a single data frame?), but with significantly more work than just calling knit2pdf.
filename <- "texi2pdf"
f_tex <- paste0("latex/", filename, ".tex")
f_pdf <- paste0("latex/", filename, ".pdf")
knit("latex/test.Rnw", output = f_tex)
tools::texi2pdf(file = f_tex, clean = TRUE, quiet = FALSE)
file.rename(from = paste0(filename, ".pdf"), to = f_pdf)
And in this case the PDF output (texi2pdf.pdf) is simply, and correctly,
This is a test
I am running R 3.3.2 and all packages are up to date.
The solution as outlined by Yihui Xie on Github is to append the output file with '.tex'
i.e.
knit2pdf(input = "latex/test.Rnw", output = 'latex/knit2pdf.tex', clean = TRUE)
I was running knitr v1.11 which did not require this, but later versions do.
I'm creating a R Markdown document using knitr and am running into trouble using xtable to create a table. My table is very large and I'm trying to reduce the size using the size command in the print statement. The issue I'm running into is that the command seems to add two extra curly braces which show up in the PDF, one before the table and one after.
Does anyone know a way to fix this?
MWE:
---
output:
pdf_document:
keep_tex: yes
tables: true
---
```{r, results='asis', echo=FALSE}
library(xtable)
my.df <- data.frame(matrix(c(1:18),nrow=2))
glossaryprint <- xtable(my.df, caption="Summary of Terms")
print(glossaryprint,
comment=FALSE,
floating=FALSE,
size="footnotesize"
)
```
Note: The issue that is subject of the question and this answer has been resolved in xtable 1.8-2.
Although the question has been self-answered with a workaround, I think for other users some more details might be helpful.
What happens?
To understand what is happening here, we need to take a close look at the conversion steps the document undergoes on its way from RMD to PDF. The steps are:
RMD --> MD --> TEX --> PDF
Let's look at the files in reversed order:
PDF: (generated from TEX by pdflatex)
TEX: (generated from MD by pandoc)
% …
\{\footnotesize
\begin{tabular}{rrrr}
\hline
& X1 & X2 & X3 \\
\hline
1 & 1 & 3 & 5 \\
2 & 2 & 4 & 6 \\
\hline
\end{tabular}
\}
% …
MD (generated from RMD by knitr)
---
output:
pdf_document:
keep_tex: yes
---
{\footnotesize
\begin{tabular}{rrrr}
\hline
& X1 & X2 & X3 \\
\hline
1 & 1 & 3 & 5 \\
2 & 2 & 4 & 6 \\
\hline
\end{tabular}
}
RMD: (source file)
---
output:
pdf_document:
keep_tex: yes
---
```{r, results='asis', echo=FALSE}
library(xtable)
mytable <- xtable(data.frame(matrix(c(1:6), nrow = 2)))
print(mytable,
comment = FALSE,
floating = FALSE,
size = "footnotesize"
)
```
Recall: The problem is, that there are visible curly braces in the PDF. Where do they come from?
They are the result of the escaped curly braces in the TEX file (\{ and \}).
These curly braces also exist in the MD file, but there they are not escaped.
So we know two things by now: We see the curly braces because they are escaped and they are escaped by pandoc.
But why do these curly braces exist at all? print.xtable outputs them when a size is specified. The goal is to create a group and to apply size only within that group. (With floating = TRUE, no grouping by curly braces is required because there is a figure environment whithin which the size is set. The curly braces are printed anyways.)
And why does pandoc escape that pair of curly braces but leaves all the other curly braces (e.g. in \begin{tabular}) unescaped? This is because pandoc is supposed to escape special characters that are meant literally but leave raw LaTeX unescaped. However, pandoc does not know that the outer curly braces are LaTeX commands and not text.
(With floating = TRUE the problem does not occur because the curly braces are within a figure environment which is recognized as LaTeX.)
Solutions
After having understood the problem, what can we do about it? One solution has already been posted by the OP: Abstain from spefifying size in print.xtable and insert the footnotesize command manually:
---
output:
pdf_document:
keep_tex: yes
---
```{r, results='asis', echo=FALSE}
library(xtable)
mytable <- xtable(data.frame(matrix(c(1:6), nrow = 2)))
cat("\\begin{footnotesize}")
print(mytable,
comment = FALSE,
floating = FALSE
)
cat("\\end{footnotesize}")
```
However, on the long run it would be nice if xtable (current version: 1.8-0) generated LaTeX code that survives the pandoc conversion. This is quite simple: print.xtable checks if size is set and if so, inserts { before the size specification and } at the end of the table:
if (is.null(size) || !is.character(size)) {
BSIZE <- ""
ESIZE <- ""
}
else {
if (length(grep("^\\\\", size)) == 0) {
size <- paste("\\", size, sep = "")
}
BSIZE <- paste("{", size, "\n", sep = "")
ESIZE <- "}\n"
}
This small modification replaces { with \begingroup and } with \endgroup:
if (is.null(size) || !is.character(size)) {
BSIZE <- ""
ESIZE <- ""
}
else {
if (length(grep("^\\\\", size)) == 0) {
size <- paste("\\", size, sep = "")
}
BSIZE <- paste("\\begingroup", size, "\n", sep = "")
ESIZE <- "\\endgroup\n"
}
For LaTeX, this makes no difference, but as pandoc recognizes \begingroup (as oppsed to {) it should solve the problem. I reported this as a bug in xtable and hopefully the issue will be fixed in future versions.
I was able to fix this by not including the size parameter in the print statement but rather directly before and after the chunk.
\begin{footnotesize}
#chunk
\end{footnotesize}
I am running the following bit of code but for some reason when using charts.PerformanceSummary() inside a for loop it tries to make more outputs than the number of times it goes through the loop. Whereas a simple plot function seems to work fine...
Please see the .Rmd code below and then the subsequent .md file created after kniting to html...
PLOT TEST
====
```{r}
suppressPackageStartupMessages(require(PerformanceAnalytics))
for(i in 1:5){
charts.PerformanceSummary(xts(rnorm(i*1000,0.0001,0.0003),Sys.Date()-c((i*1000):1)))
}
```
```{r}
for(i in 1:5){
plot(xts(cumprod(rnorm(i*1000,0.0001,0.0003)+1),Sys.Date()-c((i*1000):1)))
}
```
Giving the following .md file
PLOT TEST
====
```r
suppressPackageStartupMessages(require(PerformanceAnalytics))
for (i in 1:5) {
charts.PerformanceSummary(xts(rnorm(i * 1000, 1e-04, 3e-04), Sys.Date() -
c((i * 1000):1)))
}
```
![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-11.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-12.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-13.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-14.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-15.png) ![plot of chunk unnamed-chunk-1](figure/unnamed-chunk-16.png)
```r
for (i in 1:5) {
plot(xts(cumprod(rnorm(i * 1000, 1e-04, 3e-04) + 1), Sys.Date() - c((i *
1000):1)))
}
```
![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-21.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-22.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-23.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-24.png) ![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-25.png)
Notice how there are 6 output plots that the frist chunk tries to connect to but there are only 5 output plots in the second chunk despite both having the same for (i in 1:5) { bit of code...
As additional information the below was the sessionInfo
sessionInfo()
## R version 3.0.0 (2013-04-03)
## Platform: x86_64-apple-darwin10.8.0 (64-bit)
##
## locale:
## [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] PerformanceAnalytics_1.1.0 xts_0.9-3
## [3] zoo_1.7-9 knitr_1.2
##
## loaded via a namespace (and not attached):
## [1] digest_0.6.3 evaluate_0.4.3 formatR_0.7 grid_3.0.0
## [5] lattice_0.20-15 stringr_0.6.2 tools_3.0.0
EDIT
I have also just run the one line it on its own, and have a semi-fix...but not one for doing multiple charts in the same chunk...
Below is the .Rmd script together with the .md output
```{r}
charts.PerformanceSummary(xts(rnorm(1000,0.0001,0.0003),Sys.Date()-c((1000):1)))
```
```{r fig.keep='last'}
charts.PerformanceSummary(xts(rnorm(1000,0.0001,0.0003),Sys.Date()-c((1000):1)))
```
the .md output
```r
charts.PerformanceSummary(xts(rnorm(1000, 1e-04, 3e-04), Sys.Date() - c((1000):1)))
```
![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-41.png) ![plot of chunk unnamed-chunk-4](figure/unnamed-chunk-42.png)
```r
charts.PerformanceSummary(xts(rnorm(1000, 1e-04, 3e-04), Sys.Date() - c((1000):1)))
```
![plot of chunk unnamed-chunk-5](figure/unnamed-chunk-5.png)
EDIT 2
As pointed out by #agstudy it looks like knitr is producing an unnecessary blank image...does anybody know how to remove it?