1

I couldn't find the answer to this in the multitude of similar, but not quite the same questions on the site. Let's say I have a character string in a variable, which is a direct representation of the plotmath expression I want to use, e.g. "R^2". How can I substitute that into an expression so it's rendered as plotmath? I'm going crazy trying every combination but I can't get it to work...

#  What I want...
mn <- "R^2"
#  Using expression directly to show what I'd like to get
plot( 1 , main = expression(R^2) )

enter image description here

#  What I tried to substitute the value of 'mn' into an expression
plot( 1 , main = expression( mn ) )
plot( 1 , main = bquote( .(mn) ) )
plot( 1 , main = bquote( paste( .(mn) ) ) )
plot( 1 , main = do.call( expression , list( mn ) ) )
plot( 1 , main = do.call( expression , list( bquote( .(mn) ) ) ) )
plot( 1 , main = do.call( expression , list( bquote( paste( .(mn) ) ) ) ) ) #getting silly
plot( 1 , main = deparse( substitute( mn , list( mn = mn ) ) ) )
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184

1 Answers1

3

Here, parse will do the trick:

mn <- "R^2"

plot(1, main = parse(text = mn))

enter image description here

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • This does seem to be a good example of a situation where there really is no good alternative to `parse()`, one of the exceptions implied by `fortunes::fortune(106)`. – Josh O'Brien Mar 26 '14 at 15:01