0

I have written a loop to install packages in R, whilst I am aware there are other methods to bulk install packages, I don't understand why the loop doesn't work: I get the error message: Error: package must be character vector of length 1. Which I don't understand because package[i] should return a character vector.

packages<-c("dplyr","ggplot")
for (i in seq_along(packages)){
print(packages[i])
if (!require(packages[i])) install.packages(packages[i]) 
}

Can anyone suggest any modifications to the above code?

Basil
  • 747
  • 7
  • 18
  • No, I want to specifically debug the above code to try and understand why it doesnt work. – Basil Sep 14 '21 at 10:39
  • Do you need the seq along? Why not just `packages<-c("dplyr","ggplot") for (i in packages){ print(i) if (!require(i)) install.packages(i) }` – Quixotic22 Sep 14 '21 at 10:45
  • 2
    I think the problem is related to the expected input format of the package name inside the `require()` function. By default it expects an unquoted name of the packages. However you can tell it to use quoted string by setting `character.only = TRUE`. Try `if (!require(packages[i], character.only = TRUE))` note that you can do the other way around with `if (!require(as.name(packages[i])))` – Paul Sep 14 '21 at 10:53

1 Answers1

1
pack <- function(x){
  for( i in x ){
    if( ! require( i , character.only = TRUE ) ){
      #  If package was not able to be loaded then re-install
      install.packages( i , dependencies = TRUE )
    }
    #  Load the package after installing
    library( i , character.only = TRUE )
  }
}

pack ( c("dplyr","ggplot2"))
Nad Pat
  • 3,129
  • 3
  • 10
  • 20