Unload Package without Restarting R (Example)
This tutorial explains how to unload a package without restarting R (or RStudio).
The article is structured as follows:
- Step 1: Install & Load Package in R
- Step 2: Unload Package without Restarting R
- Video & Further Resources
Here’s the step-by-step process:
Step 1: Install & Load Package in R
I’m going to use the stringr package for the example of this R tutorial. Let’s install and load the package to R:
install.packages("stringr") # Install stringr package library("stringr") # Load stringr package
The package contains many add-on functions for the manipulation of character strings in the R programming language. For instance, we can use the str_sub function to subset certain characters of a character string:
str_sub(string = "ABCDE", start = 2, end = 4) # Apply str_sub function # "BCD"
Works fine. Now let’s assume we don’t need the package anymore and for that reason we want to remove the package from our R session…
Step 2: Unload Package without Restarting R
detach("package:stringr") # Detach stringr package
Note that within the detach function we have to write package: in front of the name of the package (i.e. stringr).
Now, let’s see whether the detaching worked. If we apply the str_sub function again, the following happens:
str_sub(string = "ABCDE", start = 2, end = 4) # Apply str_sub function
Figure 1: Error Message after Unloading stringr Package.
The function does not exist anymore. We successfully removed the stringr package from our R session!
Video & Further Resources
In case you need further explanations on the removal of packages from an R session, you may have a look at the following video that I have recently published on my YouTube channel. In the video, I’m explaining the example of this tutorial in more detail:
Furthermore, you could have a look at the other R tutorials of this website. Some interesting tutorials can be found below:
- Detach All User-Installed Packages in R
- Find Out Which Package Version is Loaded
- Check if Package is Missing and Install Automatically
- Load Multiple Packages at Once in R
- Introduction to the pacman Package in R
- The attach & detach Functions in R
- R Functions List (+ Examples)
- The R Programming Language
At this point of the article, you should know how to detach a package without closing/shutting down and reopening R (or RStudio). In case you have any further questions, please let me know in the comments section below.