Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 761
Heisenberg Avatar asked Oct 24 '17 17:10

Heisenberg


People also ask

How do I load a local package in R?

Local Installation of R Packages To install a R package locally, specify the local directory where you want to install by using the “-l” option in the “R CMD INSTALL” command. For example, to install the R package in the local directory “/usr/me/localR/library”, use the “R CMD INSTALL” as follows.

Do I have to reinstall R packages?

You shouldn't have to re-install packages each time you open R. If library(dynlm) doesn't work without re-installing then I would say this is definitely an issue. However, you do generally need to load the packages you want to use in that session via library() .

How do I update installed packages in R?

The easiest way to update R is to simply download the newest version. Install that, and it will overwrite your current version. There are also packages to do the updating: updateR for Mac, and installr for Windows.


1 Answers

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

like image 146
Mako212 Avatar answered Oct 07 '22 02:10

Mako212