关于r:为LaTeX编译清理字符串的函数吗?

Function to sanitize strings for LaTeX compilation?

虽然xtable()有一个sanitize.text.function参数,该参数允许使用特殊字符清理字符串以阻止LaTeX编译破坏Sweave / knitr文档,但该软件包不会将函数导出到用户空间。

如何在xtable上下文之外清理诸如asdf_text之类的字符串,以便将其转换为诸如asdf\\_text之类的东西? (如果可能的话,我希望有一个小的独立的解决方案。)


除非我误解了您的问题,否则我认为您忽略了latexTranslate,它也位于Hmisc程序包中(并记录在与?latex相同的帮助页面上):

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

1
2
3
4
5
library("Hmisc")
latexTranslate("asdf_text")
## [1]"asdf\\\\_text"
latexTranslate("a^2")
## [1]"a$^{2}$"


到目前为止,我发现了提供sanitizestr()

的软件包reportRx

Sanitizes strings to not break LaTeX

Strings with special charaters will break LaTeX if returned 'asis' by knitr. This happens every time we use one of the main reportRx functions. We first sanitize our strings with this function to stop LaTeX from breaking.

1
2
3
require(reportRx)
sanitizestr("asdf_text")
## [1]"asdf\\\\_text"

但是我的抱怨是它带有很多依赖项...

另一种解决方案是tikzDevice,它提供了sanitizeTexString(),并且具有更少的强制性依赖项:

Replace LaTeX Special Characters in a String

This function is used by tikzDevice when sanitize=TRUE to replace special LaTeX characters [..]

1
2
3
require(tikzDevice)
sanitizeTexString("asdf_text")
## [1]"asdf{\\\\_{}}text"