R Tutorial: Packages and Namespaces

R packages use namespaces to keep functions organized separately from the global environment. The double-colon operator (::) lets you call a specific package's function, and the conflicted package helps when two packages have functions with the same name.
Chapters
R packages are wonderful things. When we use an R package, we get a number of benefits for free. For example, when interacting with R, we live in a wonderful global environment. Any objects we create are placed inside this environment or this box. We can view the contents of the box with the LS function, but any mildly complex analysis quickly fills up this box. The consequences? We lose track of what's going on. And even worse is we might mix up two objects and start introducing hard to find bugs. When we load a package, the contents of the package isn't placed into the global environment. Instead, it's loaded into its namespace. I think of namespaces as A box contains all the package functions. The namespace keeps things tidy. It's just like a folder on your desktop. Now, when we use a library function, we get direct access to this package box. We can see the functions or the exported functions more precisely by the get namespace exports. The dplyr package has over 200 exported functions. Sometimes we want to specify exactly which box a function belongs to. We can do that with a double colon operator. Now, great minds think alike, or so the saying goes. And package authors are just the same. Take the filter function in the stats package. Filter is used for manipulating time series. Bindiplier is used to remove rows from a data frame. So the million pound question is if I type filter, which function do I get? The answer is it depends. It depends on the order the packages were loaded in. The search function returns this order. R goes through each environment looking for the object you want. It returns the object it comes to that matches your request. The global environment is always first on this list. Then the order is determined by the package load order. Namespace clashes, that is when two functions have the same name, are a pain and can lead to hard to diagnose bugs. A relatively new package aims to make this process a little bit easier. The conflicted package automatically highlights potential package clashes and forces the user, I.e. us, to make a clear choice. For example, suppose we load the dplyr package when we come to use the filter function, the conflicted package highlights issue and makes us explicitly choose right. Time to wake up and put what we've discussed.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







