knitr 中带下划线的内联代码

use*_*755 5 r knitr

我想在 LaTeX+knitr 文档中插入名为“test_sample()”的函数作为内联 R 代码。

简单地包含\Sexpr{'test_sample()'}会导致Missing $错误。

我发现以下直接相关的问题: Pass underscore as inline code to knitR

但已经复制答案中的代码对我来说不起作用:我收到一条 R 警告消息:

In hilight(code, "latex", ...) :
  the syntax of the source code is invalid; the fallback mode is used
Run Code Online (Sandbox Code Playgroud)

在 LaTeX 中仍然出现Missing $错误。

我尝试采用它

<<>>=
test_ = function(x){gsub("([_])", '\\\\\\_', "test_x")}
@
\Sexpr{test_(sample)} 
Run Code Online (Sandbox Code Playgroud)

但这仍然会导致相同的错误。

如果我手动在 knit 生成的 tex 文件中\的 th 前面放置一个转义字符_,它可以工作,但我不知道如何自动执行此操作。

当我复制粘贴这个问题的解决方案时,我也遇到了同样的错误:R, Sweave, LaTeX - escape variables to be print in LaTeX?

<<echo=FALSE>>=
sanitize <- function(str) {
  result <- str
  result <- gsub("&", "\\\\&", result, fixed = TRUE)
  result <- gsub("_", "\\\\_", result, fixed = TRUE)
  result
}
@ 

<<>>=
(foo <- "test & _")
sanitize(foo)
@ 

When sanitized, it's ``\Sexpr{sanitize(foo)}''.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

use*_*330 2

这与 R 或 R 没有任何关系knitr,这只是在 LaTeX 中插入下划线。最简单的方法是将其放入\verb命令中,例如

When sanitized, it's ``\verb!\Sexpr{sanitize(foo)}!''.
Run Code Online (Sandbox Code Playgroud)

运行后knitr,这会变成

When sanitized, it's ``\verb!test \\& \\_!''.
Run Code Online (Sandbox Code Playgroud)

这显示了你可能想要的,即 在此输入图像描述

如果需要,您可以更改该sanitize()函数以添加包装器。\verb任何产生“After”行的东西。

编辑添加:

如果您确实想保持代码突出显示,则需要执行类似https://tex.stackexchange.com/questions/70652/alltt-packages-alltt-makes-a-newline的操作来创建一个宏来执行某些操作\verb确实如此,但不是全部。这还需要更改您的清理功能。