title: escaping special latex characters in R
body: <p>Edit:
  Found function latexTranslate in package Hmisc. Seems to be what I was looking for.</p>
  
  <p>Is there an R-function escaping special latex-characters (after using cat). </p>
  
  <p>i.e.</p>
  
  <pre><code>char &lt;- "Some # special &amp; chars ^ in \this &gt; text"
  cat(someFunction(char))
  </code></pre>
  
  <p>expected Output:
  Some # special \&amp; chars \^ in $\backslash$this $>$ text</p>
  
  <p><a href="https://i.stack.imgur.com/npmAD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/npmAD.png" alt="enter image description here"></a></p>
  
  <p>if not, any ideas about how to do it myself. All my attempts with gsub etc. failed because of escaping of "\". What I've done so far...</p>
  
  <pre><code>escapeLatexSpecials &lt;- function(x) {
    x &lt;- gsub("\\", "$\\backslash$", x, fixed = T)
    x &lt;- gsub("#", "\\\\#", x)
    x &lt;- gsub("$", "\\\\$", x)
    x &lt;- gsub("%", "\\\\%", x)
    x &lt;- gsub("&amp;", "\\\\&amp;", x)
    x &lt;- gsub("~", "\\\\~", x)
    x &lt;- gsub("_", "\\\\_", x)
    x &lt;- gsub("^", "\\\\^", x)
    x &lt;- gsub("\\{", "\\\\{", x)
    x &lt;- gsub("\\}", "\\\\}", x)
    x &lt;- gsub("&gt;", "$&gt;$", x)
    x &lt;- gsub("&lt;", "$&lt;$", x)
    return(x)
  }
  
  cat(escapeLatexSpecials("Some # special &amp; chars ^ in \this &gt; text"))
  \^Some \# special \&amp; chars ^ in     his $&gt;$ text\$
  </code></pre>