mercredi 29 août 2018

Checking for, installing, and loading packages in for loop in R [duplicate]

This question already has an answer here:

this is my first post on SO, so forgive me if the formatting is wanting.
I'm trying to write a utility script that checks whether required packages are installed and installs the packages if not installed. I am trying to use a for loop to do this. For example,

requiredpackages <- c("FinancialMath", "FinCal", "ggplot2")

for (pkg in requiredpackages) {
  if (pkg %in% rownames(installed.packages()) == FALSE)
  {install.packages(pkg)}
  if (pkg %in% rownames(.packages()) == FALSE)
  {library(pkg)}
}

When I run this script, however, I get the following error message: "Error in library(pkg) : there is no package called ‘pkg’"

What am I doing wrong?

Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire