编辑:在包Hmisc中找到函数latexTranslate。似乎是我要找的东西。
是否有R函数转义特殊的乳胶字符(使用cat之后)。
即
char <- "Some # special & chars ^ in \this > text"
cat(someFunction(char))
Run Code Online (Sandbox Code Playgroud)
预期输出:$ \反斜杠$ this $> $文本中有一些特殊的\&chars \ ^
如果没有,我自己如何做的任何想法。我对gsub等的所有尝试均因转义“ \”而失败。到目前为止我所做的...
escapeLatexSpecials <- function(x) {
x <- gsub("\\", "$\\backslash$", x, fixed = T)
x <- gsub("#", "\\\\#", x)
x <- gsub("$", "\\\\$", x)
x <- gsub("%", "\\\\%", x)
x <- gsub("&", "\\\\&", x)
x <- gsub("~", "\\\\~", x)
x <- gsub("_", "\\\\_", x)
x <- gsub("^", "\\\\^", x)
x <- gsub("\\{", "\\\\{", x)
x <- gsub("\\}", "\\\\}", x)
x <- gsub(">", "$>$", x)
x <- gsub("<", "$<$", x)
return(x)
}
cat(escapeLatexSpecials("Some # special & chars ^ in \this > text"))
\^Some \# special \& chars ^ in his $>$ text\$
Run Code Online (Sandbox Code Playgroud)
latexTranslate()在 Hmisc 包中找到函数。似乎就是我一直在寻找的东西。
-OP
install.packages("Hmisc"); library(Hmisc) # or alternatively, pacman::p_load(Hmisc)
latexTranslate(char)
# [1] "Some \\# special \\& chars $^{}$ in \this $>$ text"
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请阅读文档:
https://rdrr.io/cran/Hmisc/man/latex.html