Package Loading and Conflicting Management

This page contains the information about packages loading and conflict resolving

Installing and Loading Packages

Brief Overview of Differnt Package Loading Methods

When using built-in R functions

install.packages(packagename) # install package every time, even though the package is already installed
library(packagename) # If the package is not found, an error will be raised

When using pacman::p_load(), it only installs packages when the package is not found on the system. Note here we don’t load the package {pacman}. Instead, we only use the p_load() function directly from this package.

pacman::p_load("packagename1", "packagename2") 

Installing Packages from a user-specified CRAN Mirror Site

When you install packages using install.packages() method, you may encounter the following message:

--- Please select a CRAN mirror for use in this session ---

You can either follow the GUI to choose your desire mirror site (which requires TCL/TK), or you can simply pass an argument repos without the GUI tool, e.g.:

install.packages('RMySQL', repos='http://cran.us.r-project.org')

Here is the full list of CRAN mirror sites.

Note

Read more information from this Stack Overflow discussion.

Conflict Resolving

By default, R uses the function of the package that was loaded THE LAST. Instead of relying on this built-in mechanism, it’s a good practice to manage package confilicts explicitly.

E.g. there are two common functions with the same name but come from different packages:

  • dplyr::filter()
  • stats::filter()

We can use the {conflicted} package to deal with the conflict.

# (install &) load packages
pacman::p_load(
    conflicted, 
    tidyverse)

# handle function conflicts
conflicts_prefer(dplyr::filter) 
[conflicted] Will prefer dplyr::filter over any other package.
External resources
  • https://schmidtpaul.github.io/dsfair_quarto/ch/misc/usefulthings.html#conflicted

Removing Packages

Here’s a good example of removing a package along with its dependencies.