Home > Blockchain >  Loop and If statement to check and load packages
Loop and If statement to check and load packages

Time:05-26

Why wont require take a vector of packages? Also is there a way to split pkg for both install.package and BiocManager? Thus, if packages fails to install with install.package, check with BiocManager?

Error: [1] "stringr" Loading required package: i Error in print.default("trying to install", i) : invalid printing digits -2147483648 In addition: Warning messages: 1: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called ‘i’ 2: In print.default("trying to install", i) : NAs introduced by coercion

pkg <- c("stringr", "openxlsx")

for (i in pkg){
    print(i)
    if(require(i)){
       print(i, "is loaded correctly")
    } else{
       print("trying to install", i)
       install.packages(i)
       if(require(i)){
          print(i, "installed and loaded")
       } else{
          stop("could not install", i)
       }
    }

}

CodePudding user response:

There are were at least 3 errors in that for loop. First, a missing argument to the first require,

... then failing to set the character.only argument for requireto TRUE so that i can get evaluated rather than taken as a package name, (see ?require Arguments section)

... and finally, failing to join the desired character values in the print calls with paste. (See ?print.default's Argument section. The print function only prints its first argument. Its second argument is the number of digits, as stated by the console error message.)

pkg <- c("stringr", "openxlsx")

for (i in pkg){
    print(i)
    if(require(i, character.only=TRUE)){
        print(paste(i, "is loaded correctly"))
    } else{
        print(paste("trying to install", i))
        install.packages(i)
        if(require(i, character.only=TRUE)){
            print(paste(i, "installed and loaded"))
        } else{
            stop(paste("could not install", i))
        }
    }
}

I did get : "Warning message: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called ‘openxlsx’" after the first run of that loop which I do not understand (since the message [1] "openxlsx installed and loaded" was printed, and the package did get installed and could be loaded. I'm guessing it had something to do with these activities being done within a function and there was some mismatch of environments??? When I removed pkg:openxlsx and re-ran my code I do not get the warning message.

  • Related