Easily update R packages after a fresh install

Every time a new version of R is released I face the persistent issue of how to shift over to the new version with minimal disruption to my workflow.

The most troublesome part of this shift for me is transitioning my packages to the new version of R. There are plenty of ways to do this, many of which are included in this StackOverflow post.

  • You can manually copy the “library” folder from an older R directory to the newer one, then update packages via R

  • You can install the “installr” package

  • You can avoid the problem entirely by setting .libPaths() to another directory on your computer

All good options. But I thought I’d share a few lines of code that do the work for me. The approach is to (1) identify the library for the previous version of R, (2) get a list of the installed packages based on subdirectory names (excluding those associated with the basic functioning of R), and (3) install them to your new parent folder.

Here’s the code:

### step 1: find library folder in previous version of R
dirs <- dir(substr(.libPaths()[1], 1, regexpr("/[^/]*$", 
     .libPaths()[1])[1]), full.names = TRUE)
# NB: on my ubuntu linux machine I use a modified version: 
# dirs <- dir(substr(.libPaths()[1], 1, regexpr("/[^/]*$", 
#     .libPaths()[1] - 1)[1]), full.names = TRUE)
newDir <- dirs[length(dirs)]
oldDir <- dirs[length(dirs) - 1]


### or the library directories can be manually entered
# oldDir <- "C:/Users/username/Documents/R/win-library/3.4"
# newDir <- "C:/Users/username/Documents/R/win-library/3.5"

### step 2: get a vector with names of installed, non-base packages
pkgs <- dir(path = oldDir)
pkgs.new <- pkgs[!pkgs %in% dir(newDir)]

### step 3: re-install!
install.packages(pkgs.new)

This uses the CRAN-oriented install.packages() command so it won't update packages that were downloaded from GitHub. But it's still a time saver.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: