require()和library()的区别是什么?


当前回答

这似乎是一个已经加载的包的区别。 虽然require和library都不加载包。库在检查和退出之前会做很多其他的事情。

无论如何,我建议将“require”从运行2mil次的函数的开头删除,但如果出于某种原因,我需要保留它。从技术上讲,Require是一种更快的检查。

microbenchmark(req = require(microbenchmark), lib = library(microbenchmark),times = 100000)
Unit: microseconds
 expr    min     lq      mean median     uq        max neval
  req  3.676  5.181  6.596968  5.655  6.177   9456.006 1e+05
  lib 17.192 19.887 27.302907 20.852 22.490 255665.881 1e+05

其他回答

在日常工作中,“一”并不多。

然而,根据这两个函数的文档(通过输入?在函数名和按enter键之前),require在函数内部使用,因为它会输出一个警告,如果没有找到包则继续,而library将抛出一个错误。

require()的另一个好处是它默认返回一个逻辑值。如果包已加载,则为TRUE,否则为FALSE。

> 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

所以你可以在下面这样的结构中使用require()。如果你想把你的代码分发到我们的R安装包可能不会被安装,这非常方便。

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

你会看到:

library(package) and require(package) both load the package with name package and put it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, call detach(unload = TRUE) or unloadNamespace first.) If you want to load a package without putting it on the search list, use requireNamespace.

我最初的理论是,库加载包,不管它是否已经加载,也就是说,它可能会重新加载一个已经加载的包,而require只是检查它是否加载,或者如果它没有加载就加载它(因此在依赖于某个包的函数中使用)。然而,文档反驳了这一点,并明确指出这两个函数都不会重新加载已经加载的包。

这似乎是一个已经加载的包的区别。 虽然require和library都不加载包。库在检查和退出之前会做很多其他的事情。

无论如何,我建议将“require”从运行2mil次的函数的开头删除,但如果出于某种原因,我需要保留它。从技术上讲,Require是一种更快的检查。

microbenchmark(req = require(microbenchmark), lib = library(microbenchmark),times = 100000)
Unit: microseconds
 expr    min     lq      mean median     uq        max neval
  req  3.676  5.181  6.596968  5.655  6.177   9456.006 1e+05
  lib 17.192 19.887 27.302907 20.852 22.490 255665.881 1e+05