[R] Dealing with parentheses within variable names

Duncan Murdoch murdoch.duncan at gmail.com
Sat Mar 2 14:50:06 CET 2013


On 13-03-01 12:57 PM, Duncan Murdoch wrote:
> On 01/03/2013 11:20 AM, William Dunlap wrote:

>> 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
>>                       ^
>
> Thanks.  That one looks relatively easy to fix.

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



More information about the R-help mailing list