# How to use \sexpr{} with variable that has “_” in it (i.e. avoid “math mode” error)

I am using knitr in R to write up a document in LaTex. Below a certain of code, I would like to refer to a variable I used in R.

<<chunk>>
var <- "ENSEMBL_MART_ENSEMBL"
@

In this chunk, we use the following parameters:
\begin{itemize}
\item first blah blah
\item parameter: \Sexpr{var}
\end{itemize}


When I try to compile, I keep on getting the errors:

"Missing $inserted" "LaTex Error: Command \item invalid in math mode" "LaTeX Error: Something's wrong--perhaps a missing \item."  I think that it is the fact I have some "" in the variable name: I have had this problem before (although not when specifically using \Sexpr{}). I did some testing and indeed, if the variable doesn't have a "", I don't get an error. For various reasons, I cannot rename my variable: it has to be named like so for my code to work. So my question is: how can I make LaTex understand it and not think I am going in math mode? Thanks ## 2 Answers Print as verbatim is one approach, but what if you do not want the teletype font, bute the default font? In LaTeX, "_" is an active character like % or $ , so except in verbatim mode, you should use \_ to see printed a low line character (U+005F in UTF8).

To pass a string from R to LaTeX, you must also escape any backslash character, so R should produce \\_ to have _ in plain LaTeX. You can write the R string in this way, or use a sanitize function. Example:

\documentclass{article}

\begin{document}
<<chunk>>=
var <- "ENSEMBL_MART_ENSEMBL"
var
svar <- xtable::sanitize(var,type="latex")
svar
@
\begin{itemize}
\item parameter: \verb|\Sexpr{var}|
\item parameter: \Sexpr{svar}
\end{itemize}
\end{document}


But alternatively, you can also use variable names without active LaTeX characters (maybe ENSEMBL.MART.ENSEMBL or EsemblMartEnsembl or ...) :)

Ok, I've worked it out: if you use \verb, it works:

<<chunk>>
var <- "ENSEMBL_MART_ENSEMBL"
@

In this chunk, we use the following parameters:
\begin{itemize}
\item first blah blah
\item parameter: \verb!\Sexpr{var}!
\end{itemize}