Packages and Namespaces

Defensive R Programming

Dr. Colin Gillespie

Jumping Rivers

Your global environment

  • The default environment is the .GlobalEnv
  • Objects are stored in environments
  • To view the contents, use ls()
  • This environment quickly fills up
  • We can start to mixing up objects
n
# or did I want
N
Defensive R Programming

Packages and environments

  • Packages use namespaces as spaces for names
    • You can think of a namespace as a box that contains the package
  • A namespace helps keep things tidy
    • Sort of like folders
Defensive R Programming

Exported functions

  • library() gives you direct access to this package box
  • library("dplyr") gives you direct access to the exported functions in dplyr
## 238 exported functions
getNamespaceExports("dplyr")
  • Alternatively, we can use :: to directly access a function
## The filter function from dplyr
dplyr::filter
Defensive R Programming

Great minds think alike

  • Sometimes package authors come with the same function name
## The filter() function
stats::filter()
dplyr::filter()
  • If I type filter() which version do I get?
  • It depends on the package load order!
Defensive R Programming

Great minds think alike

  • search() to the rescue
search()
# [1] ".GlobalEnv"         "package:dplyr"      "package:stats"  
# <Other packages>
Defensive R Programming

Be defensive

Namespace clashes are more than just a pain

  • They can lead to hard to diagnose bugs
Defensive R Programming

The conflicted package tries to make your function choice explicit

library("conflicted")
library("dplyr")
filter
#Error: [conflicted] `filter` found in 2 packages.
#Either pick the one you want with `::` 
# * dplyr::filter
# * stats::filter
#Or declare a preference with `conflict_prefer()`
# * conflict_prefer("filter", "dplyr")
# * conflict_prefer("filter", "stats")
Defensive R Programming

Time to wake up

Defensive R Programming

Preparing Video For Download...