How R finds objects (or, what that :: operator is for)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
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
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.