What is the difference between require() and library()?

前端 未结 8 1226
情话喂你
情话喂你 2020-11-22 11:00

What is the difference between require() and library()?

8条回答
  •  感动是毒
    2020-11-22 11:46

    Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

    > test <- library("abc")
    Error in library("abc") : there is no package called 'abc'
    > test
    Error: object 'test' not found
    > test <- require("abc")
    Loading required package: abc
    Warning message:
    In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
      there is no package called 'abc'
    > test
    [1] FALSE
    

    So you can use require() in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.

    if(require("lme4")){
        print("lme4 is loaded correctly")
    } else {
        print("trying to install lme4")
        install.packages("lme4")
        if(require(lme4)){
            print("lme4 installed and loaded")
        } else {
            stop("could not install lme4")
        }
    }
    

提交回复
热议问题