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.)
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}$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With