# Modified from https://github.com/plynty/bls-ce-r-tools/blob/master/CE_PUMD_Wrangler.R # Function that installs and librarys as many packages as you want in one sweep # This action is similar to the utils::install.packages function # just simplified/custom for my needs # Parameters: string of package(s) name(s) # fOnlyEnsureInstalled if TRUE does not load packages... # Usage: library.packages("data.table","dplyr","stringr","dtplyr") # Returns a matrix of packages and status of install and load/attachment library.packages <- function( ..., fOnlyEnsureInstalled=FALSE, characterOnly=TRUE ){ if (characterOnly) { packages <- eval(match.call()[[2]]) } else { #packages <- unlist(list(...)) packages <- as.character(match.call(expand.dots = FALSE)[[2]]) } if (length(packages) == 0) { return(invisible()) } .librarySinglePackage <- function(targetPackage){ if(!(as.character(targetPackage) %in% installed.packages())) { cat("Couldn't find the package in installed packages.\n Attempting to install ", targetPackage,"...\n", sep="") install.packages(as.character(targetPackage), dependencies = TRUE) } if (fOnlyEnsureInstalled) { if((as.character(targetPackage) %in% installed.packages())) { cat("Package ",targetPackage," is installed.\n", sep = "") return(list(targetPackage,TRUE,FALSE)) } else { cat("Failed to install package ",targetPackage,".\n", sep = "") return(list(targetPackage,FALSE,FALSE)) } } else { cat("Loading ",targetPackage,".\n", sep = "") if(try(require(as.character(targetPackage), character.only = TRUE))){ return(list(targetPackage,TRUE,TRUE)) } else { return(list( targetPackage, ((as.character(targetPackage) %in% installed.packages()) == TRUE), FALSE )) } } } .results <- matrix(unlist(lapply(packages,FUN=.librarySinglePackage)),ncol=3,byrow=TRUE) .results.logical <- matrix(as.logical(.results[,2:3]),ncol=2) colnames(.results.logical) <- c("IsInstalled","IsLoaded") rownames(.results.logical) <- .results[,1] return(.results.logical) } # testIt <- library.packages("data.table","aFakePackageShouldFail","dplyr","stringr","dtplyr",characterOnly = TRUE) # testIt # testIt2 <- library.packages(data.table,aFakePackageShouldFail,dplyr,stringr,dtplyr) # testIt2