Skip to content
Prev 326483 / 398502 Next

Transferring commas in character vector to expression

Wouldn't using just
   "*\",\"*"
instead of
   "*symbol(\"\\\\54\")*"
as the replacement do the same thing?
To me it is simpler to understand.

Note that this fails if the comma is the first or last
character in the input because '*something*' is
not a valid expression.  Another problem is that '**'
is parsed the same as "^", so "a**d" is displayed as
"a Delta superscript Delta d".  One way to deal with that
problem is to strip possible '*'s from the ends of
x.lab and convert '**'s to '*'s before giving it to the parser.
   x.lab <- gsub("^\\*|\\*$", "", x.lab)
   x.lab <- gsub("\\*\\*", "*", x.lab)
as in
f1 <- function (x.lab) 
{
    x.lab <- gsub("\\*", "*Delta*", x.lab)
    x.lab <- gsub(",", "*\",\"*", x.lab)
    x.lab <- gsub("^\\*|\\*$", "", x.lab)
    x.lab <- gsub("\\*\\*", "*", x.lab)
    parse(text = x.lab, keep.source = FALSE)
}
where the code in your mail corresponds to the function f0:
f0 <- function (x.lab) 
{
    x.lab <- gsub("\\*", "*Delta*", x.lab)
    x.lab <- gsub(",", "*symbol(\"\\\\54\")*", x.lab)
    parse(text = x.lab, keep.source = FALSE)
}

Another approach is not to turn the commas into strings, but
turn anything that is not a '*' into a string.  Then you don't have
to change your code when you discover that the inputs might
contain semicolons or something else.
f2 <- function (x.lab) 
{
    x.lab <- gsub("([^*]+)", " \"\\1\" ", x.lab)
    # I put spaces around things to make it a little more readable;
    # they may not be very readable in some fonts.
    x.lab <- gsub("\\*", " * Delta * ", x.lab)
    x.lab <- gsub("^ \\*|\\* $", "", x.lab)
    x.lab <- gsub("\\*  \\*", "*", x.lab)
    parse(text = x.lab, keep.source = FALSE)
}

Use it as in
   dotchart(1:4, labels=f2(c("***d", ",,c*", "a,*d", "****")))
This code gets ugly pretty quickly so you should bury it in a function.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com