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
Package Loading and Conflicting Management
Installing and Loading Packages
Brief Overview of Differnt Package Loading Methods
When using built-in R functions
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.
::p_load("packagename1", "packagename2") pacman
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.
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
::p_load(
pacman
conflicted,
tidyverse)
# handle function conflicts
conflicts_prefer(dplyr::filter)
[conflicted] Will prefer dplyr::filter over any other package.
- 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.