A legitimate use for the stupidest variable name ever

February 2, 2011
By

(This article was first published on 4D Pie Charts » R, and kindly contributed to R-bloggers)

The help page to make.names describes how to make a valid variable name in R:

A syntactically valid name consists of letters, numbers and the
dot or underline characters and starts with a letter or the dot
not followed by a number. Names such as ‘”.2way”’ are not valid,
and neither are the reserved words.

What it doesn’t tell you is that you can generate invalid variable names and still use them perfectly well, with a bit of trickery. To create and use such “invalid” variables, you enclose their name in backquotes.

`an invalid variable` <- 69
`an invalid variable`

You can get even more pathological, if your mind is suitably fiendish.

`FALSE` <- TRUE
`...` <- "ellipsis"

The last example illustrates a danger of using these silly names. Printing `...` throws an error, though you can retrieve the contents of the variable using get("...").

The main use of these silly names is for writing obfuscated code, so the first-person shooter you’re writing in R looks like just another routine data analysis to your boss. However, I did recently find a use for what is arguably the stupidest possible variable name: a single space.

Sometimes when you view a CSV file, it is easier to see things when you have a bit of white space. Adding blank columns can provide such utility. The trouble is, since these columns have no real use from a data analysis perspective, write.csv doesn’t give you the opportunity to create blank columns willy-nilly. Here’s a little hack to do such a thing. In your data frame, include a column with name ` ` and value NA.

dfr <- data.frame(x = 1:5, ` ` = NA, y = runif(5), check.names = FALSE)
write.csv(dfr, "blank column.csv", na = "")

the CSV file contains a blank column

Is this easier than right-clicking the column header in the CSV file and selecting Insert? Probably not, but doing things in code is always more satisfying.


Tagged: hacks, r, stupid

To leave a comment for the author, please follow the link and comment on his blog: 4D Pie Charts » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.