R中library和require的區別


library和require都可以載入包,但二者存在區別。

在一個函數中,如果一個包不存在,執行到library將會停止執行,require則會繼續執行。

http://stackoverflow.com/questions/5595512/what-is-the-difference-between-require-and-library看到對二者詳細的說明。

require將會根據包的存在與否返回true或者false,

test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test#library沒有返回值
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#require有返回值
[1] FALSE

利用上面這一點可以進行一些操作。

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")
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM