Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to sanitize strings for LaTeX compilation?

While xtable() has a sanitize.text.function argument which allows to sanitize strings with special charaters to stop LaTeX compilation from breaking in Sweave/knitr documents, the package does not export the function to the userspace.

How can I sanitize strings like asdf_text outside of the xtable context, so as to have it transformed to something like asdf\_text? (If possible I would prefer a small, self-contained solution.)

like image 577
landroni Avatar asked Mar 15 '23 15:03

landroni


1 Answers

Unless I misunderstand your question, I think you've overlooked latexTranslate, which is also in the Hmisc package (and documented on the same help page as ?latex):

‘latexTranslate’ translates particular items in character strings to LaTeX format, e.g., makes ‘a^2 = a\$^2\$’ for superscript within variable labels. LaTeX names of greek letters (e.g., ‘"alpha"’) will have backslashes added if ‘greek==TRUE’. Math mode is inserted as needed. ‘latexTranslate’ assumes that input text always has matches, e.g. ‘[) [] (] ()’, and that surrounding by ‘\$\$’ is OK.

library("Hmisc")
latexTranslate("asdf_text")
## [1] "asdf\\_text"
latexTranslate("a^2")
## [1] "a$^{2}$"
like image 120
Ben Bolker Avatar answered Mar 19 '23 15:03

Ben Bolker