Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I escape characters in variable names?

Tags:

r

escaping

Sometimes it would be useful to name variables like no programmer should name his or her variables. Of course there's some good reason for conventions and limitations on stoopid variable names, but still I'd be nice. Particularly in a language like R that is used frequently to create graphs and some labels with the graphs. Thus, some labels contain variable names.

Is there a way to use something like a+b as a variable name in R? Or is there something like a display name? For example in faceting with ggplot2 such an option would be great.

p_big + facet_grid(x ~ y,scales="free") +labs(x="",y="")

# with x containing a+b, d&c 

thx for any ideas in advance!

like image 432
Matt Bannert Avatar asked Aug 26 '10 10:08

Matt Bannert


People also ask

What characters Cannot be used in variable names?

Specifically, spaces are not permitted in the variable names, as variable name must be a single word. Variable name may not start with a digit or underscore, and may not end with an underscore. Double underscores are not permitted in variable name.

Can we use special characters in variable name?

The $ sign is not allowed as the initial character of a user-defined variable. The period, the underscore, and the characters $, #, and @ can be used within variable names. For example, A. _$@#1 is a valid variable name.

How do you escape special characters?

Special characters can serve different functions in the query syntax. To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"

Why are special characters not allowed as variable names?

Fundamentally it is because they're mostly used as operators or separators, so it would introduce ambiguity. Is there any reason relate to computer architecture or organization. No. The computer can't see the variable names.


1 Answers

You can use backticks:

R> `a + b` <- 3
R> `a + b`
[1] 3

tmp <- data.frame(1:10, rnorm(10))
names(tmp) <- c("a+b", "c&d")
ggplot(tmp, aes(`a+b`, `c&d`)) + geom_point()

See also ?Quotes.

like image 119
rcs Avatar answered Oct 16 '22 09:10

rcs