[R] expression, strsplit, ...

From: baptiste Auguié <ba208_at_exeter.ac.uk>
Date: Wed, 25 Jun 2008 18:06:45 +0100


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. Received on Wed 25 Jun 2008 - 17:14:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 25 Jun 2008 - 19:31:50 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive