require() 和library() 有什么区别?
require()
和 library()
之间有什么区别?
What is the difference between require()
and library()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
require()
和 library()
之间有什么区别?
What is the difference between require()
and library()
?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(8)
日常工作中,这样的事情并不多。
但是,根据这两个函数的文档(通过在函数名称之前放置
?
并按 Enter 键来访问),require
在函数内部使用,因为它会输出警告并如果找不到包,则继续,而library
将抛出错误。There's not much of one in everyday work.
However, according to the documentation for both functions (accessed by putting a
?
before the function name and hitting enter),require
is used inside functions, as it outputs a warning and continues if the package is not found, whereaslibrary
will throw an error.require() 的另一个好处是它默认返回一个逻辑值。如果包已加载,则为
TRUE
;如果未加载,则为FALSE
。因此,您可以在如下结构中使用
require()
。如果您想将代码分发到我们的 R 安装中,而软件包可能未安装,那么这非常方便。Another benefit of
require()
is that it returns a logical value by default.TRUE
if the packages is loaded,FALSE
if it isn't.So you can use
require()
in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.除了已经给出的好建议之外,我还要补充一点:
最好避免使用
require()
除非您实际上将使用它返回的值,例如一些错误检查循环,例如蒂埃里给出的。在大多数其他情况下,最好使用library(),因为如果包不可用,这会在包加载时给出错误消息。如果包不存在,
require()
将失败而不会出现错误。这是查明该软件包是否需要安装(或者可能因为拼写错误而根本不存在)的最佳时机。尽早并在相关时间获取错误反馈将避免追踪后续代码在尝试使用库例程时失败的原因可能带来的麻烦In addition to the good advice already given, I would add this:
It is probably best to avoid using
require()
unless you actually will be using the value it returns e.g in some error checking loop such as given by 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
。tl;dr:
require
打破了健壮软件系统的基本规则之一:尽早失败。简而言之,这是因为,当使用
require
时,您的代码可能会产生不同的错误结果,不会发出错误信号。这种情况很少见,但并非假设!考虑一下这段代码,它会产生不同的结果,具体取决于是否可以加载 {dplyr}:这可能会导致微妙的错误结果。使用
library
而不是require
会在此处引发错误,清楚地表明出现了问题。 这很好。它还使调试所有其他故障变得更加困难:如果您在脚本开头
require
一个包并在第 500 行使用其导出,您将收到一条错误消息“object 'foo' not find” ” 在第 500 行,而不是错误“没有名为 'bla' 的包”。require
唯一可接受的用例是立即检查其返回值,如其他一些答案所示。这是一种相当常见的模式,但即使在这些情况下,最好(也是推荐的,见下文)将存在检查和包的加载分开。也就是说:在这些情况下使用requireNamespace
而不是require
。从技术上讲,
require
实际上在内部调用library
(如果包尚未附加 -require
因此执行冗余检查,因为库
还检查包是否已经加载)。下面是require
的简化实现,以说明其作用:经验丰富的 R 开发人员同意:
Yihui Xie,{knitr}、{bookdown} 和许多其他软件包的作者说道:
Hadley Wickham,他是比其他任何人都更流行的R包的作者,他说
Always use
library
. Never userequire
.tl;dr:
require
breaks one of the fundamental rules of robust software systems: fail early.In a nutshell, this is because, when using
require
, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:This can lead to subtly wrong results. Using
library
instead ofrequire
throws an error here, signalling clearly that something is wrong. This is good.It also makes debugging all other failures more difficult: If you
require
a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.The only acceptable use case of
require
is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: userequireNamespace
instead ofrequire
in these cases.More technically,
require
actually callslibrary
internally (if the package wasn’t already attached —require
thus performs a redundant check, becauselibrary
also checks whether the package was already loaded). Here’s a simplified implementation ofrequire
to illustrate what it does:Experienced R developers agree:
Yihui Xie, author of {knitr}, {bookdown} and many other packages says:
Hadley Wickham, author of more popular R packages than anybody else, says
如果您想当且仅在必要时安装软件包,则可以使用
require()
,例如:对于多个软件包,您可以使用
专业提示:
当在内部使用时在脚本中,您可以通过指定
install.packages()
的repos
参数来避免出现对话框屏幕,例如您可以将
require()
和library()
包装在suppressPackageStartupMessages()
中,以抑制包启动消息,并且还可以使用参数require(..., Quietly=T, warn.conflicts=F)
如果需要保持安装安静。You can use
require()
if you want to install packages if and only if necessary, such as:For multiple packages you can use
Pro tips:
When used inside the script, you can avoid a dialog screen by specifying the
repos
parameter ofinstall.packages()
, such asYou can wrap
require()
andlibrary()
insuppressPackageStartupMessages()
to, well, suppress package startup messages, and also use the parametersrequire(..., quietly=T, warn.conflicts=F)
if needed to keep the installs quiet.你会看到:
and you will see:
我关于差异的最初理论是,library 加载包,无论它是否已经加载,即它可能会重新加载已经加载的包,而 require 只是检查它是否已加载加载,如果没有加载则加载它(因此在依赖于某个包的函数中使用)。然而,文档反驳了这一点,并明确指出这两个函数都不会重新加载已加载的包。
My initial theory about the difference was that
library
loads the packages whether it is already loaded or not, i.e. it might reload an already loaded package, whilerequire
just checks that it is loaded, or loads it if it isn't (thus the use in functions that rely on a certain package). The documentation refutes this, however, and explicitly states that neither function will reload an already loaded package.这似乎是已加载包的差异。
虽然 require 和library 确实都不会加载包。库在检查和退出之前会做很多其他事情。
我建议无论如何从运行 200 万次的函数的开头删除“require”,但如果出于某种原因我需要保留它。从技术上讲,require 是一种更快的检查。
Here seems to be the difference on an already loaded package.
While it is true that both require and library do not load the package. Library does a lot of other things before it checks and exits.
I would recommend removing "require" from the beginning of a function running 2mil times anyway, but if, for some reason I needed to keep it. require is technically a faster check.