Wwalk Wwalk - 3 years ago 120
R Question

Odd behaviour of library() function in R

When I included janitor package with other packages, it did not load.

library(MASS, caret, stepPlr, janitor)

Error in library(MASS, caret, stepPlr, janitor) : object 'janitor' not found

When I ran that command separately with only janitor package, it got loaded into session; with no error

> library(janitor)
Warning message:
package ‘janitor’ was built under R version 3.3.3

Is there any limit with including x number of packages at a time? Or there is something wrong with my RStudio?

Answer Source

The library() function isn't meant to load multiple libraries, a better approach is to create a list of packages, and use require() to check if they are installed and if not install them. See example below:

requiredPackages <- c("MASS", "caret", "stepPlr", "janitor")

ipak <- function(pkg){
        new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
        if (length(new.pkg))
                install.packages(new.pkg, dependencies = TRUE)
        sapply(pkg, require, character.only = TRUE)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download