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

Yihui Xie xie at yihui.name
Sun Jan 5 07:15:29 CET 2014


Perhaps \code{} was redefined somewhere in your book project (the
document class, certain packages, ...). Can you try to minimize your
project and track down the problem? e.g. remove the body, keep the
preamble, and use only one instance of \code{something} in the body.
It is difficult to see what could be wrong with an example that works.

Regards,
Yihui
--
Yihui Xie <xieyihui at gmail.com>
Web: http://yihui.name


On Fri, Jan 3, 2014 at 2:09 PM, Michael Friendly <friendly at yorku.ca> wrote:
> [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