Knitr - Define Latex commands that call R functions using Sexpr

Viewed 118

I'm basically wondering how to define a new Latex command such that it allows the nesting of Sexpr and some other R function, where the Latex argument is an R object.

As fortunute happenstance, the idea somewhat is transmitted by the new command structure given below:

 \newcommand{\SomeLatexCommand}[1]{\Sexpr{"#1"}}

Where fortunately the argument is indeed shown, albeit in string. With this in mind, I was hoping upon the following command:

\newcommand{\SweetLatexCommand}[1]{\Sexpr{SomeRFunction(get("#1"))}}

However, once inside nested inside an R function, #1 is not read as a placeholder for the Latex argument, but instead as an existing R variable.

Is there a way to make the last comand work? Or else, are there also other neat ways to define Latex commands which in turn can call on any R function through R objects?

Good day,

1 Answers

No, you can't do that. The problem is the way knitr works:

R runs the knit() function (or some other knitr function). That function looks through the source for code chunks and \Sexpr calls, executes them, and replaces them with the requested output, producing a .tex file.

Then LaTeX processes that .tex file. R is no longer involved.

Since \newcommand is a LaTeX command, it is only handled in the final stage, after all R evaluation is done.

There may be a way in knitr to specify another "macro" that works the way \Sexpr works, but I don't think there's a way to have several of them.

So what you should do is write multiple functions in R, and call those to do what you want, as \Sexpr{fn1(...)}, \Sexpr{fn2(...)}, etc.

I suppose if you were really determined, you could add an extra preprocessor stage at the beginning, that went through your Rnw file and replaced all strings that looked like \SweetLatexCommand{blah} with \Sexpr{SomeRFunction(get("blah"))} and then called knit(), but that seems like way too much work.

Related