Skip to content

Instantly share code, notes, and snippets.

@tomjemmett
Last active May 3, 2023 15:43
Show Gist options
  • Save tomjemmett/5033cdf5ca078e3d254db803b7b65f7a to your computer and use it in GitHub Desktop.
Save tomjemmett/5033cdf5ca078e3d254db803b7b65f7a to your computer and use it in GitHub Desktop.
reinstall r packages after an upgrade

Reinstall R packages after an upgrade

Packages that you install in R are tied to a particular version of R, so after installing a new version none of your previously installed pacakges will remain. I tend to think of this as a feature (time for a spring clean...), and then just reinstall pacakges that I know I need (e.g. install.packages(c("tidyverse", "usethis", "devtools"))) and continue to install pacakges as I realise that I need them.

However, if you really want to reinstall the previous set of packages, the steps below will help. First, we collect a list of packages that were installed from CRAN and a list of packages that were installed from GitHub repositories. Once we have those lists, after intalling the new version of R we can load the list of those packages and reinstall them.

This script does not work for packages installed from other repositories, e.g. bioconductor, r-universe, or gitlab repositories, but it could be extended to those if needed.

before installing new version of R

library(tidyverse)

fn <- function(package) {
  pd <- packageDescription(package)
  
  if (!is.null(pd$Repository)) return (pd$Repository)
  
  if (!is.null(pd$GithubRepo)) return (paste(pd$GithubUsername, pd$GithubRepo, sep = "/"))
  
  as.character(NA)
}

tibble(package = installed.packages(priority = "NA")[,"Package"]) |>
  mutate(source = map_chr(package, fn)) |>
  filter(!is.na(source)) |>
  mutate(s = ifelse(source == "CRAN", source, "GitHub"),
         p = ifelse(source == "CRAN", package, source)) |>
  group_by(s) |>
  summarise(across(p, list)) |>
  (\(.x) set_names(.x$p, .x$s))() |>
  saveRDS("~/packages_to_install.rds")

after installing new version of R

p <- readRDS("~/packages_to_install.rds")
install.packages(p$CRAN)
devtools::install_github(p$GitHub)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment