Reputation: 9628
I am trying to write a function with a graph-output. I would like to insert a legend with a value of the argument.
For example:
f<-function(x,alpha=0.9){
....
plot(x)
legend("topleft",expression(alpha)???)
}
'expression(alpha)' should equal the current value of alpha.
Can anyone tell me how I can do it?
Upvotes: 0
Views: 224
Reputation: 263451
I don't see a test case yet, but the usual answer to this sort of question (where one portion of an expression needs to be evaluated) is bquote
with its built-in .()
function:
f<-function(x,alpha=0.9){ .... plot(x) legend("topleft", bquote(.(alpha)) ) }
The `.() function isolates the section(s) that deserve evaluation. See also the plotmath page:
?plotmath
Sometimes substitute
is needed:
alpha=0.2
substitute( alpha, list(alpha=alpha) )
#0.2
.... but most people find bquote
easier to work with.
The addtional code requested with some editing to avoid overwriting label1:
x<-seq(0,60,length=150)
y<-rnorm(150,0,10)
yy<-x+y
d<-cbind(x,yy)
m<-lm(d[,2]~d[,1])
plot(x,yy) > abline(m)
label1<-summary(m)$'r.squared'
label2<-summary(m)$'adj.r.squared'
legend("topleft", legend=bquote( R^2==.(label1)*";"~Adj.R^2==.(label2) ) )
Upvotes: 1