[R] robust definition of \code{} for a knitr-produced document

Michael Friendly friendly at yorku.ca
Fri Jan 3 21:09:59 CET 2014


[Not sure if I should post this here, or on a another list, but will try 
here first...]

For a book I'm writing using knitr .Rnw files, I would like to use 
\code{} to mark
*all* R code, without having to escape special characters that appear in R
names, formulas, etc.

In the past, I've use the LaTeX definition of \code{} in the test
file below, without problems.

However, in the context of my book project,
\code{y ~ (A + B)^2} fails, and I'm forced to use \verb|y ~ (A + B)^2|,
or for other cases explicitly escape the special characters, as
in \code{str\_length()} or \code{Arthritis\$sex}.

Below is a test file that *works*.  What I don't know is how to find out why
it doesn't work in the context of my book project.

--- begin code-test.tex ---
\documentclass{article}
\usepackage{url}
\makeatletter
\newcommand\code{\bgroup\@makeother\_\@makeother\~\@makeother\$\@makeother\^\@codex}
\def\@codex#1{{\normalfont\ttfamily\hyphenchar\font=-1 #1}\egroup}
\makeatother

\begin{document}
Testing use of code fragments with special characters without
having to escape them.

\begin{itemize}
   \item Formulas--
    code: \code{y ~ (A + B)^2};
    verb:  \verb|y ~ (A + B)^2|;
    url: \url{y ~ (A + B)^2}
   \item Underscored names--
    code: \code{str_length()};
    verb: \verb|str_length()|;
    url: \url{str_length()}
   \item \$ names--
    code: \code{Arthritis$sex};
    verb:  \verb|Arthritis$sex|;
    url: \url{Arthritis$sex}

\end{itemize}
\end{document}
--- end code-test.tex


-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list