How to Unload a Package in R (With Example)


You can use the unloadNamespace() function to quickly unload a package without restarting R.

For example, you can use the following syntax to unload the ggplot2 package from the current R environment:

unloadNamespace("ggplot2")

The following example shows how to use this function in practice.

Example: How to Unload Package in R

Suppose we load the ggplot2 package in R to create a scatter plot for some data frame:

library(ggplot2)

#create data frame
df <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8),
                 y=c(4, 9, 14, 29, 24, 23, 29, 31))

#create scatterplot
ggplot(df, aes(x=x, y=y)) +
  geom_point()

We’re able to successfully use functions from the ggplot2 package to create a scatter plot.

However, suppose we no longer have a need for ggplot2 and we wish to unload the package from our current R environment.

We can use the following syntax to do so:

#unload ggplot2 from current R environment
unloadNamespace("ggplot2")

Now if we attempt to use functions from the ggplot2 package, we will receive an error:

#create data frame
df <- data.frame(x=c(1, 2, 3, 4, 5, 6, 7, 8),
                 y=c(4, 9, 14, 29, 24, 23, 29, 31))

#create scatterplot
ggplot(df, aes(x=x, y=y)) +
  geom_point()

Error in ggplot(df, aes(x = x, y = y)) : could not find function "ggplot"

We receive an error because the ggplot2 package is no longer loaded in our current R environment since we unloaded it using the unloadNamespace() function.

Related: How to Check which Package Version is Loaded in R

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Clear the Environment in R
How to Create a Multi-Line Comment in R
How to Check which Package Version is Loaded in R

Leave a Reply

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