How to Unload a Package Without Restarting in R

To unload a package without restarting in R, you can use the detach() function with unload argument set to TRUE. The detach() function takes the arguments package:<package_name> and the unload argument TRUE to ensure the package is fully unloaded.


# Unload ggplot2 package
detach(package:ggplot2, unload=TRUE)

First, we loaded the ggplot2 package using the library() function and then unloaded it using the detach() function with the unload argument set to TRUE. This will unload the ggplot2 package and its namespace from your current R session.

Remember that unloading a package using detach() might not work as expected in some cases, especially when the package has dependencies or has modified the global environment. In such cases, it’s often better to restart your R session to ensure a clean environment.

You can also use the unloadNamespace() function to quickly unload a package without restarting R. For example, to unload the ggplot2 package from the current R environment, use this syntax: unloadNamespace(“ggplot2”).

How to unload multiple versions of the package in R

To unload all the versions of the package in R, you can this custom function. It is possible to have multiple package versions loaded at once (for example, if you have a development version and a stable version in different libraries).


detach_package <- function(pkg, character.only = FALSE) {
  if (!character.only) {
    pkg <- deparse(substitute(pkg))
  search_item <- paste("package", pkg, sep = ":")
  while (search_item %in% search()) {
    detach(search_item, unload = TRUE, character.only = TRUE)

detach_package("ggplot2", TRUE)

How to unload the package in RStudio

To unload the package in RStudio, you can restart your R session by clicking on the “Session” menu at the top and selecting “Restart R” or by pressing the Ctrl+Shift+F10 keyboard shortcut (or Cmd+Shift+F10 on macOS).

That’s it.

Leave a Comment