Display the source of a knitr code snippet in a document

I am trying to output the source of a knitr block to a beam slider.

For example, I would like the following code snippet to appear as in .Rnw:

<<code-chunk, echo=TRUE, tidy=TRUE>>= @ 

I tried to recreate this behavior using:

 <<out-first-code-chunk, echo=FALSE, comment=NA>>= cat(paste("<<example-code-chunk, echo=TRUE, tidy=TRUE>>=","@",sep="\n")) @ 

This code is legal since the cat command in the R console gives:

 > cat('<<example-code-chunk, echo=TRUE, tidy=TRUE>>=','@',sep='\n') <<code-chunk, echo=TRUE, tidy=TRUE>>= @ 

However, the resulting latex:

 \begin{frame} \frametitle{Code Chunk} To incorporate R code into your knitr documents \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{verbatim} <<example-code-chunk, echo=TRUE, tidy=TRUE>>= @ \end{verbatim} \end{kframe} \end{knitrout} 

It produces errors:

 <<example-code-chunk, echo=TRUE, tidy=TRUE>>= @ \end {verbatim} \end \ETC. ! Paragraph ended before \@xverbatim was complete. <to be read again> \par l.198 \end{frame} I suspect you've forgotten a `}', causing me to apply this control sequence to too much text. How can we recover? My plan is to forget the whole thing and hope for the best. ! LaTeX Error: \begin{verbatim} on input line 198 ended by \end{ beamer@framepau ses}. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.198 \end{frame} Your command was ignored. Type I <command> <return> to replace it with another command, or <return> to continue without it. ! LaTeX Error: \begin{kframe} on input line 198 ended by \end{ beamer@frameslide }. 

Why does latex medium think it's literally not closed? Is there a more suitable way to display the piece code as a whole?

+7
r knitr latex
source share
1 answer

That should do it ...

1 line in the installation fragment and 1 additional parameter in the fragment, which is required for output ...

Console:

 `install.packages(devtools)` `devtools::install_github("thell/knitliteral")` 

For .Rnw :

 <<"knitr-setup", include=FALSE, cache=FALSE>>= knitLiteral::kast_on() @ <<"my_chunk", eval=FALSE, opts.label="literal-literal">>= # Something that will not be output in the doc. @ 

Output:

 <<"my_chunk", eval=FALSE>>= @ 

For .Rmd :

 ````{r knitr_setup, include=FALSE, cache=FALSE} knitLiteral::kast_on() ```` ````{r my_chunk, opts.label="literal-literal"} # Something that will not be output in the doc. ```` 

Output:

 ````{r my_chunk} ```` 

** Using 4 backticks saves syntax highlighting as a valid R (where used).

From this snippet and what you can see in the source of the Literal Markdown doc and rendered doc example , there is no need to have a complex snippet.

A sweave example file is also available showing the same examples.

+4
source share

All Articles