Skip to content
Home » How to load a single function from an R library

How to load a single function from an R library


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’: 


By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!

Happy selective importing!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

1 thought on “How to load a single function from an R library”

Leave a Reply

Your email address will not be published. Required fields are marked *