10

How do I use variables in Latex expressions in R?

For example:

plot(X, Y, main=expression(R^2))

Will put R with a nice superscripted 2 as main title.

But let's say I want it to say 'R^2: 0.5', with 0.5 coming from a R variable. How do I do that?

c00kiemonster
  • 22,241
  • 34
  • 95
  • 133

4 Answers4

14

The hack of Owen is pretty cool, but not really the common way to do that. If you use bquote, this is actually pretty easy. bquote will do the same as quote, with the exception that everything between .() will be evaluated in a specified environment (or the global, if nothing is specified).

A trivial example :

X <- 1:10
Y <- 1:10
a <- 0.8
plot(X,Y,main=bquote(R^2 : .(a)))

Gives :

enter image description here

See also ?bquote and ?plotmath for more examples and possibilities

Joris Meys
  • 106,551
  • 31
  • 221
  • 263
  • Nice! I've often wanted something like bquote() but never knew it existed. – Owen Jul 28 '11 at 09:39
  • Yup that worked just nice. Weird though it's such a hassle to mix latex and r variables. – c00kiemonster Jul 28 '11 at 10:19
  • 1
    @c00kiemonster R isn't and never was meant as a LaTeX processor. R's `plotmath` functionality has to work within the confines of R syntax and conventions of the parser. Once you get used to it, it is a lot easier than it seems. – Gavin Simpson Jul 28 '11 at 13:41
3

Well this works...

call(':', quote(R^2), a)

though it feels a little hacky to me since it's using R's : operator, whereas you just want to stick some text on the end. Maybe there's a better way?

Owen
  • 38,836
  • 14
  • 95
  • 125
3

tikz and psfrag allow you to use actual LaTeX code and output instead of plotmath's, resulting in better typographic consistency.

See this question for details. Getting LaTeX into R Plots

Community
  • 1
  • 1
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142
2

Another variation on @Joris' theme is substitute(). You give substitute() an expression and an environment or list within which to evaluate the expression. Passing a list is usually easiest, especially for jobs such as the one posed here.

plot(X,Y, main = substitute(R^2 : a, list(a = a)))

We can see why this works, by looking solely at the substitute() call:

> substitute(R^2 : a, list(a = a))
R^2:0.8

The a in the expression is replace with the value of a in the list.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453