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

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

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

相关标签:
8条回答
  • 2020-11-22 11:45

    There's not much of one in everyday work.

    However, according to the documentation for both functions (accessed by putting a ? before the function name and hitting enter), require is used inside functions, as it outputs a warning and continues if the package is not found, whereas library will throw an error.

    0 讨论(0)
  • 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")
        }
    }
    
    0 讨论(0)
提交回复
热议问题