简体   繁体   English

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

[英]R, Sweave, LaTeX - escape variables to be printed in LaTeX?

I've been searching for the past 2 days, and while I've found similar questions on Stack Overflow and other discussions on Google, I've found nothing matching my request. 我一直在搜索过去的两天,虽然我在Stack Overflow和Google上的其他讨论中发现了类似的问题,但我发现没有任何内容符合我的要求。

I have a pre-existing application that I'm supporting, which is built around R. Sweave Rnw template files are used to generate .tex files, which are used to generate .pdf files. 我有一个我支持的预先存在的应用程序,它是围绕R构建的.Sweave Rnw模板文件用于生成.tex文件,用于生成.pdf文件。

Within the Rnw, there is existing code such as this: 在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}

The issue is, myReport$courseInfo$shortname has values that need to be escaped for LaTeX, as it includes characters such as & (which forces LaTeX to toss an error about the table columns). 问题是,myReport $ courseInfo $ shortname具有需要为LaTeX转义的值,因为它包含诸如&的字符(这会强制LaTeX抛出关于表列的错误)。 I've attempted including the seqinr library, and using stresc on the entire data object, but still the generated .tex file shows an unslashed & from shortname. 我试图包含seqinr库,并在整个数据对象上使用stresc,但生成的.tex文件仍显示unslashed&from shortname。

I'm not wholly familiar with R yet, but in playing around with the template, I've found that the calls to "print()" above are not even needed, as just specifying the variables directly within \\Sexpr results in printed values, but still my escaped values are unescaped when recorded in the .tex. 我还不完全熟悉R,但是在使用模板时,我发现甚至不需要上面的“print()”调用,因为只需在\\ Sexpr中直接指定变量就会产生打印值,但是在.tex中记录时,我的转义值仍未转义。

I've also attempted to place stresc directly within the \\Sexpr (instead of print), with no difference. 我还尝试将stresc直接放在\\ Sexpr(而不是print)中,没有区别。

So it seems that R/Sweave's own process is stripping the slashes, which means I likely need to double-slash values, but I'm not familiar enough with R to know how to do that. 所以似乎R / Sweave自己的进程正在剥离斜线,这意味着我可能需要双重削减值,但我不熟悉R知道如何做到这一点。

What is the proper way to print dynamic data into a .tex file? 将动态数据打印到.tex文件的正确方法是什么?


UPDATE : Based on @Aaron's response, here is the function I created: 更新 :基于@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);
}

My updated template (as referenced in my original post above) now looks like this: 我的更新模板(在我上面的原始帖子中引用)现在看起来像这样:

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

So a string with an & now properly shows up in the generated LaTeX file as: 因此,带有&的字符串现在可以在生成的LaTeX文件中正确显示为:

Some string \\& some other string 一些字符串\\和其他一些字符串

You can either use \\verb or you can insert a quadruple backslash, which is needed to get one in the final tex file because it goes through two printing operations which convert a double "\\" to a single "\\". 您可以使用\\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}

The Hmisc package has a latexTranslate function designed to prepare strings for Latex. Hmisc包有一个latexTranslate函数,用于为Latex准备字符串。 From its helpfile: 从它的帮助文件:

latexTranslate translates particular items in character strings to LaTeX format, eg, makes a^2 = a\\$^2\\$ for superscript within variable labels. latexTranslate将字符串中的特定项目转换为LaTeX格式,例如,在变量标签中为上标生成^ 2 = a \\ $ ^ 2 \\ $。 LaTeX names of greek letters (eg, "alpha") will have backslashes added if greek==TRUE. 如果greek == TRUE,希腊字母的LaTeX名称(例如“alpha”)将添加反斜杠。 Math mode is inserted as needed. 根据需要插入数学模式。 latexTranslate assumes that input text always has matches, eg [) [] (] (), and that surrounding by \\$\\$ is OK. latexTranslate假定输入文本始终具有匹配项,例如[] [](](),并且\\ $ \\ $周围的条件正常。

\\verb命令可以帮助你吗?

Or you could also use Sweave to make the table; 或者你也可以使用Sweave制作桌子; when using tex output instead of Sexpr only a double backslash is needed, as my sanitize1 does here, or stresc does more completely. 当使用tex输出而不是Sexpr只需要一个双反斜杠,因为我的sanitize1在这里做,或者stresc更完整。

You'd fill d in with your values ( myReport$report_name instead of "My_Report_Name" , for example) instead of the ones I made up. 你会填补d与你的价值观( myReport$report_name而不是"My_Report_Name" ,例如),而不是我做了的人。

<<echo=FALSE, results=tex>>=
sanitize1 <- function(str) {
  result <- str
  result <- gsub("&", "\\&", result, fixed = TRUE)
  result <- gsub("_", "\\_", result, fixed = TRUE)
  result
}
d <- rbind(c("Report name:","My_Report_Name"),
           c("Report date:","\\today"),
           c("Course name:","STAT101"),
           c("Start date:", "23 Mar 2011"),
           c("Instructor:", "Aaron & Jon L."))
cat("\\begin{tabular}{lll}\n")
for(i in 1:nrow(d)) {
  cat("& {\\textbf{",d[i,1],"}} &", sanitize1(d[i,2]), "\\\\\n", sep="")
}
cat("\\end{tabular}\n")
@ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM