在文档中显示knitr代码块源

时间:2014-06-01 00:20:36

标签: r latex knitr

我试图将knitr chunk的来源输出到beamer幻灯片上。

例如,我希望以下代码块显示在.Rnw中:

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

我尝试使用以下方法重新创建此行为:

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

这段代码是合法的,因为R&#39的控制台中的cat命令给出了:

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

然而,产生的乳胶:

\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}

引发错误:

<<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 }.

为什么乳胶环境认为逐字不关闭?有没有更合适的方式来完整地显示代码块?

1 个答案:

答案 0 :(得分:4)

应该这样做......

设置块中的1行,以及输出所需的块中的1个额外参数...

控制台:

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

.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.
@

输出:

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

.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.
````

输出:

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

**使用4个反引号将语法高亮保持为有效R(使用时)。

从这个块以及您在示例Literal Markdown doc和rendered doc的源代码中可以看到的内容,您无需拥有复杂的块。

sweave example file也可以显示相同的示例。