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