[R] getting to a point where packages are installed and "ready to use", without unnecessarily reinstalling packages

Kelly Thompson kt1572757 @end|ng |rom gm@||@com
Tue Oct 25 15:54:03 CEST 2022

I have R packages I want to use.

Q. What is the "best" way to get to a point where all of the packages
are installed and "ready to use", AND where I only install or
re-install a package if doing so is needed?

#I searched the web for insights and found these:

Based on what I read there, I "think" I should use the require function.

Here is what I came up with.

Is there anything "wrong" with this code, and are there any ways I can
improve the code?


#install and load packages (list the packages I want in a vector,
check if they are available to use, install if needed, load and
attach, review)

#create a vector with the character vector of the name(s) of
package(s) I want to use
packages_i_want_to_use <- c('RODBC', 'data.table', 'matrixStats',
'plyr', 'MASS', 'dplyr', 'lubridate')
#packages_i_want_to_use <- c("this_pac_does_not_exist", "abcz", "lubridate")

#use the require function to check if the package(s) is (are) available
packages_exist_true_false <- sapply(X = packages_i_want_to_use, FUN =
require, character.only = TRUE, quietly = TRUE)

# create a vector with the names of the packages that need to be installed
packages_to_install <-
packages_i_want_to_use[packages_exist_true_false == FALSE]

#specify the repo(s) AKA CRAN mirror I want to use
myrepo <- 'https://ftp.osuosl.org/pub/cran/'

#install the package(s)
install.packages(pkgs = packages_to_install, repos = myrepo)

#load and attach the packages_i_want_to_use using the library function
sapply(X = packages_i_want_to_use, FUN = library, character.only = TRUE)

#review to determine if the packages are available, using require()
packages_exist_true_false_review <- sapply(X = packages_i_want_to_use,
FUN = require, character.only = TRUE, quietly = TRUE)


More information about the R-help mailing list