How R finds objects (or, what that :: operator is for)

April 4, 2012
By

(This article was first published on Revolutions, and kindly contributed to R-bloggers)

Most of the time when we're programming in R, we don't think about how R gets from an object name (say, "stdev") to what it represents (a function to calculate standard deviation, perhaps). If you're writing functions, you've probably know about R's lexical scoping. And if you use a lot of packages, you probably know about the search list, the sequence of packages that R looks in for an object if it can't be found in the local environment. But if you've ever wondered what an "environment" actually is, or the specifics of the rules that R actually uses to find objects by name, don't miss Suraj Gupta's excellent article, "How R Searches and Finds Stuff". 

This is deep stuff, but it's also a fascinating look into R's inner workings. R seems like a simple language, so you might be surprised at the complexity behind the name-lookup process, which Suraj describes as "following the purple line road" in the diagram below.

Map-of-the-world-complete

As Suraj poins out, given that "R is an interpreted, weakly typed language that supports attaching multiple packages at-will", a design like this is necessary to set rules for what should happen in the cases of functions calling themselves, or multiple packages that provide definitions for the same function name. He also offers some excellent advice for package developers, for example on how to set the Depends and Import attributes of your package to avoid conflict with packages the user may have installed, and how to manage package namespaces with exported and hidden symbols. Oh, and if you've ever wondered what the mysterious :: and ::: operators (as in stats::sd) are for:

If you know exactly which package contains the object desired then you can reference it directly using the :: operator. Simply place the package name before the operator and the name of the object after the operator to retrieve it. 

If the object is not exported or you are unsure, then you can use the ::: operator (notice the extra colon).

Read the whole, fascinating article at the link below.

O Beautiful Code: How R Searches and Finds Stuff

To leave a comment for the author, please follow the link and comment on his blog: Revolutions.

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.