[R] substituting string variable in expression with its value

William Dunlap wdunlap at tibco.com
Thu Sep 12 18:27:30 CEST 2013


Is this what you want?

myTitle <- function (name, unitsExpr = parse(text = unitsString)[[1]], unitsString) 
{
    name <- as.name(name)
    bquote(.(name) ~ "[" * .(unitsExpr) * "]")
}
plot(1,1,xlab=myTitle("velocity", quote(km/hr)), ylab=myTitle("distance", quote(light~years)))

Note that unitsExpr should be an expression (typically as quote(...)) but
if you hate expressions you can give a string to unitsString, which will
be parsed to form the expression.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Jannis
> Sent: Thursday, September 12, 2013 7:53 AM
> To: Gerrit Eichner
> Cc: r-help at r-project.org
> Subject: Re: [R] substituting string variable in expression with its value
> 
> Hi Gerrit,
> 
> thanks for your suggestion. I want to create some code were I can supply
> the 'm*s^{-2}' part as an argument to a function and which evaluates
> this as an expression to use Rs mathematical annotation features in the
> labels.
> 
> 
> Any further ideas?
> 
> Jannis
> 
> 
> 
> On 12.09.2013 14:28, Gerrit Eichner wrote:
> > Hi, Jannis,
> >
> > maybe
> >
> > plot( 1, 1, main = bquote( paste( .(a), " [", .(b), "]")))
> >
> >
> > comes close to what you want, but I think you may even have to use the
> > following to get a varying exponent really printed elevated:
> >
> > a <- "speed"
> > b <- "m * s"
> > cc <- -2
> >
> > plot( 1, 1, main = bquote( paste( .(a), " [", .(b)^{.(cc)}, "]")))
> >
> >
> >
> >  Hth  --  Gerrit
> >
> >
> >> plot(1,1, main=expression(paste("speed [", m * s^{-1}, "]")))
> >>
> >>
> >> I would, however, like to be able to supply the value "speed" and
> >> m*s^{-a} by variables, e.g. do something like:
> >>
> >>
> >> a = 'speed'
> >> b = 'm*s^{-2}'
> >>
> >> plot(1,1, main=expression(paste(a, " [", b, "]")))
> >>
> >> This, however, does not work as a and b are not treated as variable
> >> names in this case. Does anyone have a solution for this?
> >>
> >>
> >> Cheers
> >> jannis
> >>
> >> ______________________________________________
> >> R-help at r-project.org mailing list
> >> https://stat.ethz.ch/mailman/listinfo/r-help
> >> PLEASE do read the posting guide
> >> http://www.R-project.org/posting-guide.html
> >> and provide commented, minimal, self-contained, reproducible code.
> >
> >
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list