I'm working on a script to check and update packages if they're out of date. Below is what I've got so far, but on startup (click .Rproj which runs the script in my Rprofile) the session goes into an infinite loop. I was getting this warning:
Error in install.packages : cannot remove prior installation of package ‘haven’
So I remove.packages('haven') and deleted the folder in /R/library.
After running again in a new session, from the output it looks like it tries to redownload and install haven 4(!) times before finishing. Can anyone spot why or offer some tips about this workflow?
Last thing I'll add is that I've seen some other very helpful answers recommending require()
which I will probably switch to using, but haven't gotten to yet.
Thanks!
### load needed packages
# set up list of important packages
# check if they're installed
# if not, install
# check if they're updated
# if not, update
#list of necessary packages
listOfPackages <- c('tidyverse', #'tidyselect','readr','readxl','stringr','sjlabelled','forcats',
'lubridate',
'writexl',
'haven',
'janitor',
'glue',
'reshape2',
'skimr',
'codebook',
'labelled')
#loop to load packages, and install if not installed previously
# i <- 8
for (i in listOfPackages) {
# set local CRAN mirror
local({
r <- getOption("repos")
r["CRAN"] <- "https://cloud.r-project.org"
options(repos = r)})
if (!i %in% utils::installed.packages()) {
# repos 1 chooses the cloud version "closest"
utils::install.packages(i,
dependencies = TRUE,
repos = 1)
}
# if installed update
else {
# ask = false stops prompt for all updates
utils::update.packages(oldPkgs = listOfPackages,
ask = FALSE)
}
}
## print a list of important packages installed
# filter to packages we want to know about
pkgs <- tibble::tibble(
Package = names(utils::installed.packages()[, 3]),
Version = unname(utils::installed.packages()[, 3])
)
# print the packages we care about and their versions
cat("These are the important libraries loaded and their versions.",
"\n",
"If you need to use a new package, please add it to the 'listofPackages in pkg_check.R",
"\n")
print(pkgs[grep(paste0(listOfPackages, collapse = "|"),
pkgs["Package"][[1]]), ])