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.