# How to put R code into a parameter of a newcommand?

I would like to put R code into a parameter of a newcommand in LaTeX. To do it, I make the following:

%Define the newcommand:
\newcommand\solution[1]{\sf #1}

%Then, after the \begin{document}, I write:

\solution{
<<echo=T>>=
x=rnorm(100)
@
}


in my .Rnw file. After I do R CMD Sweave file.Rnw, all is OK but when I do pdflatex file.tex, the response is:

! FancyVerb Error:
Extraneous input > x=rnorm(100) \end {Sinput} \end {Schunk} ' between \begin
{Sinput}[<key=value>] and line end
.
\FV@Error ... {FancyVerb Error:
\space \space #1
}

l.12 }


Somebody can help me?

-
Welcome to TeX.SX. A tip: If you indent lines by 4 spaces, then they're marked as a code sample. You can also highlight the code and click the "code" button ({}) or select your code and hit Ctrl+K. – Claudio Fiandrino Feb 7 '13 at 12:09
Can you say more about what you're trying to accomplish? Sweave inserts its own LaTeX environment, so it's not surprising at all that just wrapping the results in \sf would fail. It will probably be easier to debug by working on the LaTeX file produced by Sweave ... – Ben Bolker Feb 7 '13 at 13:54

The chunks are verbatim like structures, thus cannot be used inside \macro{....}, make a solution environment instead (BTW use \sfseries, not \sf)

You might get away with just

\newenvironment{solution}{\sffamily}{}

\begin{solution}
<<echo=T>>=
x=rnorm(100)
@
\end{solution}
`
-
Thank you for the response. In fact, what I want to do is a little bit more complicated: I want to create a "solution" environment for my exams but I want to control when the solutions appears. To do it, I do the following: – arnau Feb 8 '13 at 10:18
See the comment package, it can switch environments on and off. Or use environ package to make an envelope that some times eats up its contents without typesetting it – daleif Feb 9 '13 at 13:02