Handle duplicate packages in different paths

If you work with multiple work stations (multiple computers/laptops) sharing the same cloud folder. You might encounter this problem. Your Rstudio in different computers will have different default paths to install and load packages. For each computer, you will see something like this:

  1. Cloud-path: “Users/yourname/cloud_drive/Documents/R/win-library/version
  2. Local-path: “Program Files/R/R_version/library”

To see your library path, type .libPaths() in the console.

To always have the same library path on multiple devices, you have to create .Renviron on each device

usethis::edit_r_environ()

After opening the .Renviron file, type in R_LIBS_USER = "file_path" where “file_path” is your desired cloud location.

To remove all duplicate packages, you can either remove them based on version (solution by this post) or based on path location

library(tidyverse)
pkgs <- installed.packages()
pkgs <- as.data.frame(pkgs)

# get the list of duplicate packages
dupes <- pkgs %>% select(Package, Version, LibPath) %>% 
  group_by(Package) %>% 
  filter(n_distinct(Version, na.rm = TRUE) > 1)

# remove duplicate packages
# delete packages based on library path
dupes %>%
  mutate(chosen_path = if_else(LibPath == "chosen_file_path_to_keep", 1, 0)) %>%
  filter(chosen_path != 1) %>% 
  purrr::pmap(~ remove.packages(..1, ..3))
 
dupes %>%
  # delete packages based on version (delete older ones)
  group_by(Package) %>%
  arrange(desc(Version)) %>%
  filter(Version != first(Version)) %>%
  purrr::pmap(~ remove.packages(..1, ..3))
Mike Nguyen, PhD
Mike Nguyen, PhD
Visitng Scholar

My research interests include marketing, and social science.

Next
Previous

Related