[R] Dealing with parentheses within variable names
William Dunlap
wdunlap at tibco.com
Fri Mar 1 17:20:00 CET 2013
> R shouldn't have trouble with names like that
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
> If you find functions in base R that object to those names, I think we'd
> like to fix them.
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
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Duncan Murdoch
> Sent: Thursday, February 28, 2013 1:46 PM
> To: Jesus Munoz Serrano
> Cc: r-help at r-project.org
> Subject: Re: [R] Dealing with parentheses within variable names
>
> On 28/02/2013 11:08 AM, Jesus Munoz Serrano wrote:
> > Dear all
> >
> > I'm having some problems with a data set that has parenthesis within the variable
> names. A example of this kind of variable names is the following:
> >
> > fBodyGyroskewness()Z
> >
> > The case is that R is having a lot of troubles to identify the variable (probably it does
> understand it like a function). I've tried (among other things) to remove the parenthesis
> from the name using the following command:
> >
> > names(dataFrame) <- sub("()","", names(dataFrame))
> >
> > but It didn't work. Sorry if it's a silly issue but I would really appreciate if anybody could
> help me. Thank you very much.
> R shouldn't have trouble with names like that, but a lot of packages
> will (e.g. the ones that construct strings and call parse() on them).
> If you find functions in base R that object to those names, I think we'd
> like to fix them. If the functions are in contributed packages, your
> mileage may vary.
>
> Duncan Murdoch
>
> ______________________________________________
> 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.
More information about the R-help
mailing list