[R] expression, strsplit, ...

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 25 20:45:07 CEST 2008


Try this:

plot(1, xlab = ~ alpha / V * m^-3 * kg ^-2 * l^4)


On Wed, Jun 25, 2008 at 1:06 PM, baptiste Auguié <ba208 at exeter.ac.uk> wrote:
> DeaR list,
>
> I'm a bit lost in the behavior of substitute and co.
> I often use fairly long axis labels in my graphs (long to write, that is).
> Typically, they would contain some greek letters and units with exponents,
> as in:
>
>>        xlab=expression(paste("text ", alpha, " / ", V,".", m^{-3}, ".",
>> kg^{-2}, ".", l^{4}))
>
>
> To make this a bit prettier, I've attempted to mimic the behavior of the
> SIstyle latex package which defines a macro that cleverly parses an
> expression for units, exponents, etc. My code fails in putting together the
> unit, as seen in the example below:
>
>>
>> makeUnits <- function(expr){ # formats the units
>>
>> units.list <- strsplit(expr, "[[:blank:]]", perl=F)
>> expr.list <- strsplit(unlist(units.list), "\\^", perl=T)
>>
>> units <- unlist(lapply(expr.list, function(unit) {
>>                if (length(unit) == 2)
>> paste(unit[1],"^{",unit[2],"}",sep="")
>>                else paste(unit,sep="")
>>                }))
>>        cat(units, sep=".")
>> }
>>
>> expr <- "V m^-3 kg^-2 l^4"
>> makeUnits(expr) # this works, and produces:
>
> # V.m^{-3}.kg^{-2}.l^{4}
>>
>> silab <- function(..., units=NULL){ # creates a valid expression for xlab
>> and co.
>>        dotCalls <- substitute(list(...))
>>        nArgs <- length(dotCalls)
>> if (!is.null(units))    myUnits <- makeUnits(units)
>> if (!is.null(units)) return(substitute(paste(..., " / ",  myUnits)))
>> if (is.null(units)) return(substitute(paste(...)))
>> }
>>
>> silab("text", alpha,  units = "V m^-3 kg^-2 l^4") # the result is
>> obviously not what I want
>>
>> par(mfrow=c(2, 1)) # comparison of the desired output and the current one
>> plot(1:10, 1:10,
>>        xlab=silab("text ", alpha, units = "V m^-3 kg^-2 l^4"),
>>        ylab=silab("simple text"))
>>
>> plot(1:10, 1:10,
>>        xlab=expression(paste("text ", alpha, " / ", V,".", m^{-3}, ".",
>> kg^{-2}, ".", l^{4})),
>>        ylab="simple text")
>
>
>
>
> Any thoughts welcome!
>
> Sincerely,
>
> baptiste
>
> _____________________________
>
> Baptiste Auguié
>
> Physics Department
> University of Exeter
> Stocker Road,
> Exeter, Devon,
> EX4 4QL, UK
>
> Phone: +44 1392 264187
>
> http://newton.ex.ac.uk/research/emag
> http://projects.ex.ac.uk/atto
>
> ______________________________________________
> 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