0

Since I work on different PCs with same script, I always need to install packages, thus my package loading argument is always if(!require("ggplot2")){install.packages("ggplot2"); library(ggplot2)} (ggplot2 as an example).

So I want to write a function as the title describes, my thought was

load_packages <- function(package){ if(!require(package)){install.packages(package); library(package)} }

however despite it can install package through load_packages("ggplot2"), it can't load as it says

Error in library(package) : there is no package called ‘package’

Negrito
  • 220
  • 1
  • 9
  • 2
    Use `character.only=TRUE` in call to `library`? Because then `library` will evaluate `package` and not take it as the name of a package. See`?library`. – Bhas Jan 13 '20 at 07:30
  • 1
    `if(!require(pkg,character.only =TRUE)){install.packages(pkg);require(pkg,character.only =TRUE)}` – Onyambu Jan 13 '20 at 07:51
  • 1
    Why not use the pacman::p_load() function ? The pacman package is quite an efficient package manager ! – Emmanuel Daveau Jan 13 '20 at 08:53

0 Answers0