[R] Combining plaintext and plotmath expressions

Leif Kirschenbaum leif at reflectivity.com
Thu Mar 2 21:10:58 CET 2006


I searched the archives and did not find a solution, so I pose this question to those well-versed in the use of plotmath and expressions.

I have a list of strings in an external CSV file which I wish to use sometimes as plot axis labels and sometimes as plot titles.  These strings combine plaintext and a few mathematical expressions (Greek letters, subscripts). Moreover, I sometimes need to concatenate other plaintext with these strings. Thus far I have written my string list to look like this:

"X translation ("*mu*"m)"
"Rotation ("*degree*")"
"Mean ("*mu*"m)"
"Vb1-Vb2 "*(Omega)
H[2]O "Used"
Max P
# Defects

I read in the strings, and use one at a time in the variable "parmlabel".
I have another variable called "testlabel" which I also need to concatenate, and can be things like "distance" or "E-test". Sometimes I also concatenate another variable "oplabel" when the variable "op" is not zero-length.

I have kludged a solution using this function:


expr.label<-function(title=""){
## single quote the character # so that it is not interpreted as a comment
  parmlabel<-gsub("#","'#'",cfg$parmlabel[icfg])
## make sure that a string like "Vb1-Vb2" is not interpreted as subtraction
  text1<-gsub("-","*'-'*",testlabel)
## if need to prepend title test, do that, and make multiple spaces single
  if(nchar(title)) text1<-paste(gsub("  "," ",title)," ",testlabel,sep="")
## substitute to avoid interpretation of "for"
  text1<-gsub("for","f*or",text1,fixed=TRUE)
## substitute ~ for spaces to avoid errors in parsing
  text1<-gsub(" ","~",text1,fixed=TRUE)
## see if we have a parsable expression
  text2<-try(parse(text=parmlabel),silent=TRUE)
## if not parsable then concatenate another way
  if(class(text2)=="try-error" | length(text2)==0){
    text2<-gsub(" ","~",parmlabel)
    exprtitle<-paste(text1,text2,sep="~")
  } else{ exprtitle<-paste('"',text1,'~"*',text2,sep='') }
  exprtitle<-paste(text1,text2,sep="~")
## if the variable op is not zero-length, then use oplabel
  if(nchar(op)>1) exprtitle=paste(exprtitle,'~',gsub(' ','~',oplabel),sep="")
  return(exprtitle)
}

As an example:

> parmlabel<-'"Vb1-Vb2 "*(Omega)'
> testlabel<-'E-test'
> op<-'dev lab'
> oplabel<-'Development Lab'
> expr.label("SPC Chart for")

I then use exprtitle in:

   plot(1:10,title= if(plotnum==1) parse(text=exprtitle) else NULL)

However:
  this code seems convoluted and ungainly
  I don't always get the results I want

Any suggestions?

Leif Kirschenbaum
Senior Yield Engineer
Reflectivity, Inc.
(408) 737-8100 x307
leif at reflectivity.com




More information about the R-help mailing list