Files
language-conditioned-psycho…/research/environment/install-r-packages.R
T

49 lines
1.7 KiB
R

command_args <- commandArgs(trailingOnly = FALSE)
script_path <- sub("^--file=", "", grep("^--file=", command_args, value = TRUE)[1])
script_dir <- dirname(normalizePath(script_path, winslash = "/"))
project_root <- normalizePath(file.path(script_dir, "..", ".."), winslash = "/")
library_path <- file.path(project_root, ".r-library", "4.6")
dir.create(library_path, recursive = TRUE, showWarnings = FALSE)
.libPaths(c(library_path, .libPaths()))
required_packages <- c(
"survey", "srvyr",
"mirt",
"lavaan", "semTools", "psych",
"data.table", "jsonlite", "arrow", "haven", "readr",
"dplyr", "tidyr", "purrr", "stringr",
"digest", "renv", "targets", "withr"
)
installed <- rownames(installed.packages(lib.loc = .libPaths()))
missing <- setdiff(required_packages, installed)
if (length(missing) > 0L) {
install.packages(
missing,
lib = library_path,
repos = c(CRAN = "https://cloud.r-project.org"),
dependencies = c("Depends", "Imports", "LinkingTo"),
type = "binary",
Ncpus = max(1L, parallel::detectCores(logical = TRUE) - 2L)
)
}
installed_after <- rownames(installed.packages(lib.loc = .libPaths()))
still_missing <- setdiff(required_packages, installed_after)
if (length(still_missing) > 0L) {
stop("Missing R packages after installation: ", paste(still_missing, collapse = ", "))
}
versions <- vapply(
required_packages,
function(package) as.character(packageVersion(package, lib.loc = library_path)),
character(1)
)
writeLines(
jsonlite::toJSON(as.list(versions), pretty = TRUE, auto_unbox = TRUE),
file.path(script_dir, "r-package-versions.json"),
useBytes = TRUE
)
cat("Installed and verified", length(required_packages), "required R packages.\n")