【发布时间】:2018-06-06 08:20:40
【问题描述】:
在LyX/LaTeX 文档中,我使用knitr 包含(R)代码块。
我想通过重复内联部分来解释我的代码在块下方。
如何实现相同的内联文本格式(无需评估)?
亿辉在doing this in rmarkdown和另一个another answer by him that it should be similar in LaTeX上有一个问答,但是当我尝试使用rmarkdown答案中的代码时,它会在LyX中抛出错误。
我得到的错误是:
Error in if (knitr:::pandoc_to() != "latex") return(code) :
argument is of length zero
当我删除if (knitr .... 行时,我得到一个输出文档,但行代码被格式化为普通文本。
有什么想法吗?
编辑:根据要求提供 MWE
\documentclass{article}
\begin{document}
<<include=FALSE>>=
local({
hi_pandoc = function(code) {
if (knitr:::pandoc_to() != 'latex') return(code)
if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required')
res = highr::hi_latex(code, markup = highr:::cmd_pandoc_latex)
sprintf('\\texttt{%s}', res)
}
hook_inline = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x)
})
})
@
Test inline R code: \Sexpr{ I("plot(cars, main = 'A scatterplot.')") }.
Normal inline code \Sexpr{pi}.
A code block:
<<>>=
plot(cars, main = 'A scatterplot.')
1 + 2 # a comment
@
\end{document}
【问题讨论】:
-
请向我们提供minimal reproducible example。
-
它与 rmarkdown 的代码相同,但在 LyX 中,这有点冗长。我将在 LaTeX 中添加一些应该等效的内容。
-
当我将
\Sexpr{r pi}替换为\Sexpr{pi}时,您的 MWE 会编译。您想要更改生成的输出的哪一部分? -
啊,谢谢你发现它,它不适合我
-
plot(cars, ...的格式是否类似于 knitr 块?