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


当前回答

?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和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
?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只是检查它是否加载,或者如果它没有加载就加载它(因此在依赖于某个包的函数中使用)。然而,文档反驳了这一点,并明确指出这两个函数都不会重新加载已经加载的包。

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

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

你可以使用require()如果你想安装包当且仅当必要时,例如:

if (!require(package, character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
}

对于多个包,您可以使用

for (package in c('<package1>', '<package2>')) {
    if (!require(package, character.only=T, quietly=T)) {
        install.packages(package)
        library(package, character.only=T)
    }
}

专业提示:

在脚本中使用时,可以通过指定install.packages()的repos参数来避免出现对话框屏幕,例如 安装。包(包,回购= " http://cran.us.r-project.org ") 你可以在suppressPackageStartupMessages()中包装require()和library()来抑制包启动消息,也可以使用参数require(…,安静=T,警告。冲突=F)如果需要保持安装安静。