R,Sweave,LaTeX - 在LaTeX中打印的转义变量?

Jon*_* L. 12 latex r sweave

我一直在搜索过去的两天,虽然我在Stack Overflow和Google上的其他讨论中发现了类似的问题,但我发现没有任何内容符合我的要求.

我有一个我支持的预先存在的应用程序,它是围绕R构建的.Sweave Rnw模板文件用于生成.tex文件,用于生成.pdf文件.

在Rnw中,存在如下代码:

\begin{tabular}{lll}
& {\bf \textcolor{TitlesColor}{Report name:}} & \Sexpr{print(myReport$report_name)}\\
& {\bf \textcolor{TitlesColor}{Report date:}} & \today \\
& {\bf \textcolor{TitlesColor}{Course name:}} & \Sexpr{print(myReport$courseInfo$shortname)}\\
& {\bf \textcolor{TitlesColor}{Start date:}}  & \Sexpr{print(myReport$courseInfo$startdate_readable)}\\
& {\bf \textcolor{TitlesColor}{Instructor:}} & \Sexpr{print(paste(myReport$instructor$lastname, collapse="| "))}\\
\end{tabular}
Run Code Online (Sandbox Code Playgroud)

问题是,myReport $ courseInfo $ shortname具有需要为LaTeX转义的值,因为它包含诸如&的字符(这会强制LaTeX抛出关于表列的错误).我试图包括seqinr库,并在整个数据对象上使用stresc,但生成的.tex文件仍显示unslashed&from shortname.

我还不完全熟悉R,但是在使用模板时,我发现甚至不需要上面的"print()"调用,因为只需在\ Sexpr中直接指定变量就会产生打印值,但是在.tex中记录时,我的转义值仍未转义.

我还尝试将stresc直接放在\ Sexpr(而不是print)中,没有区别.

所以似乎R/Sweave自己的进程正在剥离斜线,这意味着我可能需要双重削减值,但我不熟悉R知道如何做到这一点.

将动态数据打印到.tex文件的正确方法是什么?


更新:基于@Aaron的回复,这是我创建的函数:

# Sanitizes variables for displaying within LaTeX via Sexpr
# Adds slashes to LaTeX special characters, which results in single-slash in tex output
sanitizeLatexS <- function(str) {
    gsub('([#$%&~_\\^\\\\{}])', '\\\\\\\\\\1', str, perl = TRUE);
}
Run Code Online (Sandbox Code Playgroud)

我的更新模板(在我上面的原始帖子中引用)现在看起来像这样:

\begin{tabular}{lll}
& {\bf \textcolor{TitlesColor}{Report name:}} & \Sexpr{sanitizeLatexS(myReport$report_name)}\\
& {\bf \textcolor{TitlesColor}{Report date:}} & \today \\
& {\bf \textcolor{TitlesColor}{Course name:}} & \Sexpr{sanitizeLatexS(myReport$courseInfo$shortname)}\\
& {\bf \textcolor{TitlesColor}{Start date:}}  & \Sexpr{sanitizeLatexS(myReport$courseInfo$startdate_readable)}\\
& {\bf \textcolor{TitlesColor}{Instructor(s):}} & \Sexpr{sanitizeLatexS(paste(myReport$instructorList$lastname, collapse="| "))}\\
\end{tabular}
Run Code Online (Sandbox Code Playgroud)

因此,带有&的字符串现在可以在生成的LaTeX文件中正确显示为:

一些字符串\和其他一些字符串

Aar*_*ica 8

你可以使用\verb或者你可以插入一个四重反斜杠,这是在最终的tex文件中获得一个,因为它经历了两个打印操作,将双"\"转换为单个"\".

\documentclass{article}
\begin{document}
<<echo=FALSE, results=hide>>=
sanitize <- function(str) {
  result <- str
  result <- gsub("&", "\\\\&", result, fixed = TRUE)
  result <- gsub("_", "\\\\_", result, fixed = TRUE)
  result
}
@ 

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

My string is ``\verb+\Sexpr{foo}+''.  When sanitized, it's ``\Sexpr{sanitize(foo)}''.

\end{document}
Run Code Online (Sandbox Code Playgroud)

  • 根据[xkcd](http://xkcd.com/1638/),这是"实际的反斜杠,这次是真实的,"并且增加更多可能会导致"反斜杠如此真实,它超越了时间和空间",或者其他更令人担忧的结果.:) (2认同)

Ani*_*iko 7

Hmisc软件包具有latexTranslate为Latex准备字符串的功能.从它的帮助文件:

latexTranslate将字符串中的特定项目转换为LaTeX格式,例如,在变量标签中为上标生成^ 2 = a\$ ^ 2\$.如果greek == TRUE,希腊字母的LaTeX名称(例如"alpha")将添加反斜杠.根据需要插入数学模式.latexTranslate假定输入文本始终具有匹配项,例如[] [](](),并且\ $\$周围的条件正常.