0
votes

I'm learning R and have written my first for-loop. For a character vector with the required packages, requiredpackages, I try to create a function named install_load that checks whether the packages within requiredpackages are already installed. If so, then it loads those packages via the library() function. Else, it installs them. However, running the code gives me the following error:

Error in install.packages : Updating loaded packages

Restarting R session...

install.packages(p) Error in install.packages : object 'p' not found**

requiredpackages <- c('ggplot2', 'ggthemes')
    
install_load <- function(packages){
for (p in packages) {
   if (p %in% rownames(installed.packages())) {
       library(p, character.only=TRUE)
       } else {
       install.packages(p)
           }
         }
       }
    
       install_load(requiredpackages)
1

1 Answers

0
votes

Change the requiredpackages object reference to packages within the function to resolve the logic error. Since packages is the name of the argument that contains the list of packages being passed to the function, it is the correct object to reference within the for() loop of the function.

You'll also want to add a library() function to the branch that installs a package so at the end of the function all required packages are both installed and loaded.

requiredpackages <- c('ggplot2', 'ggthemes')

install_load <- function(packages){
     for (p in packages) {
          if (p %in% rownames(installed.packages())) {
               library(p, character.only=TRUE)
          } else {
               install.packages(p)
               library(p,character.only = TRUE)
          }
     }
}

install_load(requiredpackages)

...and the output:

> install_load(requiredpackages)
Want to understand how all the pieces fit together? See the R for Data Science book:
http://r4ds.had.co.nz/
trying URL 'https://cran.rstudio.com/bin/macosx/el-capitan/contrib/3.5/ggthemes_4.0.1.tgz'
Content type 'application/x-gzip' length 425053 bytes (415 KB)
==================================================
downloaded 415 KB


The downloaded binary packages are in
    /var/folders/2b/bhqlk7xs4712_5b0shwgtg840000gn/T//Rtmp1yfVvz/downloaded_packages
> 

We can also use sessionInfo() to confirm that both ggplot2 and ggthemes packages have been loaded into memory:

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS  10.14.2

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggthemes_4.0.1 ggplot2_3.1.0 

...sessionInfo() output continues.