Heisenberg
Heisenberg

Reputation: 8806

How to "reinstall and reload" a local R package?

I'm implementing a statistical algorithm into an R package, which will be used in my analysis. The R package is local on my disk.

Since I'm making a lot of changes to the R package, I want my analysis script to reinstall and reload the fresh R package every time it runs.

What's the best way to do this? Currently, I use:

install.packages("~/my_package/", repos=NULL, type="source") 
library("my_package")

However, it seems like I still have to manually tell Rstudio to restart my R session for the fresh version to kick in.

Upvotes: 21

Views: 11140

Answers (1)

Mako212
Mako212

Reputation: 7292

You have to unload the current version of the package for the update to take effect when you try to load it again.

detach("package:my_package", unload=TRUE)

Note: package is literal, my_package = insert your package name here

library(dplyr)
detach("package:dplyr", unload=TRUE)

If a package is already loaded library() doesn't load it again. You can see this by running

library(dplyr, verbose=TRUE)
library(dplyr, verbose=TRUE)

The first time you run this command it loads the package, the second time it returns:

Warning message:
In library(dplyr, verbose = T) :
  package ‘dplyr’ already present in search()

library() uses a generalized form of is.na(match("package:dplyr",search())) to determine whether a package is attached or not, and so running library() alone won't update the currently loaded package since this check doesn't differentiate between package versions.

Also worth noting that you'll have to first unload any dependencies, otherwise you'll see an error to the effect of:

Warning message: ‘dplyr’ namespace cannot be unloaded: namespace ‘dplyr’ is imported by <package(s)> so cannot be unloaded

Upvotes: 19

Related Questions