I am trying to get a label to have an exponent in it. Here's the code I have
vall = format(cor(x,y)*cor(x,y),digits=3)
eq <- expression(paste(R^2," = ",vall,sep=""))
text(legend.x,legend.y,eq,cex=1,font=2)
But the text simply looks like this
How do I get the actual vall to show up (and not the text "vall")
Try bquote()
, for example:
set.seed(1)
vall <- format(rnorm(1),digits=3)
eq <- bquote(bold(R^2 == .(vall)))
sq <- seq(0, 1, by = 0.1)
plot(sq, sq, type = "n")
text(0.5, 0.5, eq)
The reason your example doesn't work is that R never ends up evaluating vall
:
> eq2 <- expression(paste(R^2," = ",vall,sep=""))
> eq2
expression(paste(R^2, " = ", vall, sep = ""))
plotmath tries to make something out of this but essentially vall
is taken literally.
In general you don't need paste()
in a plotmath expression, you can build the expression up using standard operators and through the use of layout operators. For example, for an expression equivalent to the one your example produced (unevaluated vall
), all you really need is:
expression(R^2 == vall)
bquote()
is one way to have an object replaced by its value in an expression. You wrap the object you want replaced by its value in .( )
. R will then look for the object and takes its value and insert it into the expression.
See also substitute()
for an alternative approach to this with a different interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With