="-6ren">
gpt4 book ai didi

r - 在文档中显示 knitr 代码块源

转载 作者:行者123 更新时间:2023-12-04 11:04:32 24 4
gpt4 key购买 nike

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

例如,我希望在 .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>>=
@

然而,产生的 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}

抛出错误:
<<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 }.

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

最佳答案

这个应该做...

设置 block 中的 1 行,输出所需的 block 中的 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 (在哪里使用)。

从这个 block 和你可以在示例源代码中看到的 Literal Markdown doc 和 rendered doc没有必要有一个复杂的 block 。

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

关于r - 在文档中显示 knitr 代码块源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com