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
其他回答
除了已经提出的好建议之外,我还要补充一点:
最好避免使用require(),除非你真的要使用它返回的值,例如在一些错误检查循环中,比如thierry给出的。
In most other cases it is better to use library(), because this will give an error message at package loading time if the package is not available. require() will just fail without an error if the package is not there. This is the best time to find out if the package needs to be installed (or perhaps doesn't even exist because it it spelled wrong). Getting error feedback early and at the relevant time will avoid possible headaches with tracking down why later code fails when it attempts to use library routines
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.
在日常工作中,“一”并不多。
然而,根据这两个函数的文档(通过输入?在函数名和按enter键之前),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