For the R users that are jealous of Python’s import system, there’s good news. As of R 3.6, it’s possible to include or exclude specific functions when loading a library. Importing the whole namespace is no longer required.
Selective loading of R packages
As of R 3.6, importing only one or more functions without having the load the complete namespace can be done using the include.only argument of the require and library functions. In the following snippet, you can find some examples using the stringr package.
library(stringr, include.only = 'str_length') # include one function library(stringr, include.only = c('str_length', 'str_sub')) # include multiple functions
One can also load all functions from a namespace, but exclude a selection. Like this:
library(stringr, exclude = 'str_pad') # exclude one function library(stringr, exclude = c('str_pad','str_dup')) # exclude multiple functions
Keep in mind that you cannot use both arguments in the same call. Otherwise, you’ll run into the following error message.
Error: only one of 'include.only' and 'exclude' can be used
Selective loading & dependencies
Finally, you might not be able to include or exclude one function from a package, if that function is loaded from a dependency. As an example, the tidymodels package depends on the parsnip package for the linear_reg function.
library(tidymodels, include.only = 'linear_reg') # will produce the error below library(parsnip, include.only = 'linear_reg') # this works
Error: package or namespace load failed for ‘tidymodels’: not found in namespace ‘tidymodels’: linear_reg
Happy selective importing!