【问题标题】:Display the knitr code chunk source in document在文档中显示 knitr 代码块源
【发布时间】:2014-06-01 00:20:36
【问题描述】:

我正在尝试将 knitr 块的来源输出到投影仪幻灯片上。

例如,我希望在 .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 控制台中的 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 }.

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

【问题讨论】:

  • 你可能需要\begin{frame}[fragile]:tex.stackexchange.com/questions/140719/…
  • 检查这个包knitLiteral。它允许在不使用任何cat 技巧的情况下逐字打印代码块。
  • 非常感谢你们!很有帮助。我确实需要[脆弱]。 knitLiteral 对于更复杂的代码块也非常方便。
  • @Coatless,如果您愿意,欢迎您发布我的评论版本作为答案。

标签: r latex knitr


【解决方案1】:

应该这样做...

设置块中的 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 也可以显示相同的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2023-03-29
    • 2018-12-21
    相关资源
    最近更新 更多