我一直在尋找過去的2天,雖然我發現堆棧溢出和Google上的其他討論類似的問題,但我沒有發現任何與我的請求相符的問題。R,Sweave,LaTeX - 要在LaTeX中打印的轉義變量?
我有一個我支持的預先存在的應用程序,它是圍繞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 $短名稱有需要進行轉義爲乳膠,因爲它包含的字符,如&(值這迫使LaTeX拋出關於表列的錯誤)。 我試過包括seqinr庫,並在整個數據對象上使用stresc,但仍然生成的.tex文件顯示了未命名的&短名稱。
我還沒有完全熟悉R,但是在玩模板時,我發現上面的「print()」調用是不需要的,因爲只需在\ Sexpr中直接指定變量導致打印值,但仍記錄在.tex中時,我的轉義值不轉義。
我也試圖將stresc直接放在\ Sexpr(而不是打印)中,沒有任何區別。
所以看起來R/Sweave自己的過程是剝離斜槓,這意味着我可能需要雙斜槓值,但是我對R知道如何做到這一點並不熟悉。
什麼是將動態數據打印到.tex文件的正確方法?
UPDATE: 基於@阿龍的回答,這裏是我創建的功能:
# 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文件中:
一些字符串\ &其他字符串
R-help郵件列表上的類似解決方案:http://stat.ethz.ch/pipermail/r-help/2010-November/260082.html – Aaron 2011-03-23 15:19:46
郵件列表網址給出a 404 – 2011-03-23 17:42:15
要澄清你對\ verb(你在Andrea的回答中的評論)的評論,爲了將「帶有&的一些文本」打印到tex文件中作爲「某些帶有\&包含的文本」,我會這麼做嗎?'\ verb + \ Sexpr {myReport $ courseInfo $ shortname} +' – 2011-03-23 17:47:11