過去 2 日間検索してきましたが、Google で Stack Overflow やその他のディスカッションで同様の質問を見つけましたが、私の要求に一致するものは見つかりませんでした。
私がサポートしている既存のアプリケーションは、R を中心に構築されています。Sweave Rnw テンプレート ファイルは、.pdf ファイルの生成に使用される .tex ファイルの生成に使用されます。
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 ファイルには、スラッシュなしの & from shortname が表示されます。
私はまだ R に完全に精通しているわけではありませんが、テンプレートをいじってみると、\Sexpr 内で変数を直接指定するだけで値が出力されるため、上記の "print()" の呼び出しすら必要ないことがわかりました。 、しかし、.texに記録すると、エスケープされた値はエスケープされません。
また、stresc を (print ではなく) \Sexpr 内に直接配置しようとしましたが、違いはありませんでした。
したがって、R/Sweave 独自のプロセスでスラッシュが取り除かれているようです。つまり、値を二重にスラッシュする必要がある可能性がありますが、その方法を知るほど R に精通していません。
動的データを .tex ファイルに出力する適切な方法は何ですか?
UPDATE : @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 ファイルに次のように正しく表示されるようになりました。
いくつかの文字列 \& 他の文字列