Skip to content

Dealing with parentheses within variable names

3 messages · William Dunlap, Duncan Murdoch

#
You will need to enclose the names with backquotes, `odd Name (parens)`, when using them
in expressions.  E.g.,

  > d <- data.frame(`P/E`=c(20,25,22), `% Growth`=c(2.4, 2.8, 5.0), `+-`=c(TRUE,TRUE,FALSE), check.names=FALSE)
  > # In the former you could use "P/E"=, but `P/E` works.  check.names=FALSE stops name mangling
  > d
    P/E % Growth    +-
  1  20      2.4  TRUE
  2  25      2.8  TRUE
  3  22      5.0 FALSE
  > # in the next `% Growth` is essential
  > lm(`% Growth` ~ ., data=d)
  
  Call:
  lm(formula = `% Growth` ~ ., data = d)
  
  Coefficients:
  (Intercept)        `P/E`     `+-`TRUE
         3.24         0.08        -2.44
A core R function that fails with odd names is reformulate():
   > reformulate(c("P/E", "% Growth"), response="+-")
   Error in parse(text = termtext) : <text>:1:16: unexpected input
   1: response ~ P/E+% Growth
                    ^
It works you you add the `` inside the "" (for the termlabels, but not needed
for the response argument):
  > reformulate(c("`P/E`", "`% Growth`"), response="+-")
  `+-` ~ `P/E` + `% Growth`

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
On 01/03/2013 11:20 AM, William Dunlap wrote:
Thanks.  That one looks relatively easy to fix.

Duncan Murdoch
#
On 13-03-01 12:57 PM, Duncan Murdoch wrote:
After taking a closer look, I realized that it is actually behaving as 
designed.  The first input to reformulate is supposed to be a character 
vector, not bits of R language.  For example, we want

reformulate("x*w")

to return

~ x*w

not

~ `x*w`

So you might think your example should have been entered as

reformulate(c("`P/E`", "`% Growth`"), response="`+-`")

However, this doesn't quite work:  it ends up with response having 
double backticks.  The way to get what you want is to use

reformulate(c("`P/E`", "`% Growth`"), response=as.name("+-"))

Definitely not my favourite design for a function, but I think it's not 
a code issue.  Maybe something should be added to the help page, but 
this is such an obscure issue that I'm not sure I could make things clearer.

Duncan Murdoch