How to Unload a Package in R (With Example)

In R, the unload() function can be used to unload a package that has been loaded with the library() or require() functions. This function is useful for freeing up memory when a package is no longer needed. To unload a package, simply type the unload function followed by the name of the package inside parentheses. For example, unload(“ggplot2”) would unload the ggplot2 package.


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 Create a Multi-Line Comment in R

x