How to remove all user installed packages in R

[This article was first published on Rbloggers – The Analytics Lab, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A little while ago I ran into an issue with R and RStudio. In order to solve this issue I saw myself forced to remove all user installed packages. For a lot of practical reasons it was not an option for me to simply uninstall R and start with a clean slate and a new installation of R.

Therefore I had to find another solution which could help me with removing all user installed packages. I found a few useful tips and tricks, but nothing that immediately did the job for me. That’s why I’ve decided to share my solution, I hope this can help you in the hour of need.

Here is the script I’ve created in order to remove all user installed packages, without removing any base packages for R or MRO.

# create a list of all installed packages
 ip <- as.data.frame(installed.packages())
 head(ip)
# if you use MRO, make sure that no packages in this library will be removed
 ip <- subset(ip, !grepl("MRO", ip$LibPath))
# we don't want to remove base or recommended packages either\
 ip <- ip[!(ip[,"Priority"] %in% c("base", "recommended")),]
# determine the library where the packages are installed
 path.lib <- unique(ip$LibPath)
# create a vector with all the names of the packages you want to remove
 pkgs.to.remove <- ip[,1]
 head(pkgs.to.remove)
# remove the packages
 sapply(pkgs.to.remove, remove.packages, lib = path.lib)
To leave a comment for the author, please follow the link and comment on their blog: Rbloggers – The Analytics Lab.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)