gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:07:21 26 4
gpt4 key购买 nike

过去 2 天我一直在搜索,虽然我在 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}

问题是,myReport$courseInfo$shortname 具有需要为 LaTeX 转义的值,因为它包含诸如 & 之类的字符(这会强制 LaTeX 抛出有关表列的错误)。我尝试包含 seqinr 库,并在整个数据对象上使用 stresc,但生成的 .tex 文件仍然显示来自短名称的未斜杠 &。

我还不完全熟悉 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);
}

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

\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}

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

Some string \& some other string

最佳答案

您可以使用 \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}

关于R、Sweave、LaTeX - 要在 LaTeX 中打印的转义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406071/

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