Search code examples
r-exams

Backslash symbol "\" in R environment within the string block


I have several string blocks in the R environment with "\" which is used to describe the latex symbols. However, when I use the expressions with a backslash "\" or double backslashes "\\" within \Sexpr{} in the question or answer parts, they do not really function as expected. Is there any way to properly use backslashes in R exams?


Solution

  • In standard R strings the backslash is the escape symbol and hence it also needs to be escaped itself. So you need "\\alpha" to denote the string \alpha. However, wehn you use \Sexpr{} you need to escape twice, once for reading and once for writing. Thus, you need "\\\\alpha" in that case.

    If you write German umlaut characters it becomes even worse because the " also has to be escaped, e.g., sch\\\\\"on" to write schön in LaTeX. But if you don't use this very often, it's not worth trying to remeber it. Instead apply the strategy from fortunes::fortune(365):

    When in doubt, keep adding slashes until it works.
    -- Joran Elias (on how to escape a backslash in R)
       Stackoverflow (March 2015)