How to Unload a Package Without Restarting R

All good things must come to an end. And while R packages are usually a wonderful thing, there inevitably comes a time that you need to part ways. Perhaps memory and system resources are at a premium. Perhaps that particular package happens to have a high risk of colliding with other packages you want to use in that workspace. In any event, we’re going to discuss how to unload a package without restarting R…

How to Unload a Package in R

When it comes time to unload a package in R and detach it from your R environment, there’s a very simple solution – the detach function.

# how to unload a package in r

detach("package:<package_name>", unload=TRUE)

The detach command will remove the package in question from your R work-space.

Why you may need to unload a package in R

The need for this function is driven by the nature of R package creation as an extremely decentralized activity. Individual R packages were designed and developed by separate maintainers, who may or may not coordinate with each other to manage issues such as overlapping name-spaces and common resources. While this is generally not a major issue if you’re primarily working with mainstream packages, this can become a real problem if you’re dealing with a couple of fringe packages.

R development isn’t policed by any centralized and highly aligned authorities such as the team which maintains Python’s standard library library. In practice, the larger packages are bound together by an active community of users and overlaps are relatively rare. This collaboration doesn’t really extend to the fringe of the community, however, and there are plenty of small specialty packages floating around out there.

On a related note, you may need to install separate version of the same package to manage backward compatibility in legacy code. This situation requires a similar solution, where you use detach to swap out packages.

Scroll to top
Privacy Policy