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")
    }
}
posted @ 2012-10-24 08:15  todoit  阅读(21502)  评论(0编辑  收藏  举报