require() 和library() 有什么区别?

发布于 2024-10-31 08:13:59 字数 63 浏览 9 评论 0原文

require()library() 之间有什么区别?

What is the difference between require() and library()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夜司空 2024-11-07 08:13:59

日常工作中,这样的事情并不多。

但是,根据这两个函数的文档(通过在函数名称之前放置 ? 并按 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, whereas library will throw an error.

咋地 2024-11-07 08:13:59

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

Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

> 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

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.

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")
    }
}
鸠书 2024-11-07 08:13:59

除了已经给出的好建议之外,我还要补充一点:

最好避免使用 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

失退 2024-11-07 08:13:59

始终使用。切勿使用 require

tl;dr:require 打破了健壮软件系统的基本规则之一:尽早失败

简而言之,这是因为,当使用 require 时,您的代码可能会产生不同的错误结果,不会发出错误信号。这种情况很少见,但并非假设!考虑一下这段代码,它会产生不同的结果,具体取决于是否可以加载 {dplyr}:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

这可能会导致微妙的错误结果。使用 library 而不是 require 会在此处引发错误,清楚地表明出现了问题。 这很好

它还使调试所有其他故障变得更加困难:如果您在脚本开头 require 一个包并在第 500 行使用其导出,您将收到一条错误消息“object 'foo' not find” ” 在第 500 行,而不是错误“没有名为 'bla' 的包”。

require 唯一可接受的用例是立即检查其返回值,如其他一些答案所示。这是一种相当常见的模式,但即使在这些情况下,最好(也是推荐的,见下文)将存在检查和包的加载分开。也就是说:在这些情况下使用 requireNamespace 而不是 require

从技术上讲, require 实际上在内部调用 library (如果包尚未附加 - require 因此执行冗余检查,因为 检查包是否已经加载)。下面是 require 的简化实现,以说明其作用:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

经验丰富的 R 开发人员同意:

Yihui Xie,{knitr}、{bookdown} 和许多其他软件包的作者说道

女士们先生们,我之前已经说过:require() 是加载 R 包的错误方法;使用library()代替

Hadley Wickham,他是比其他任何人都更流行的R包的作者,他说

在数据分析脚本中使用library(x)。 […]
您永远不需要使用 require()requireNamespace() 几乎总是更好)

Always use library. Never use require.

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:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require 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: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […]
You never need to use require() (requireNamespace() is almost always better)

沒落の蓅哖 2024-11-07 08:13:59

如果您想当且仅在必要时安装软件包,则可以使用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 参数来避免出现对话框屏幕,例如

    install.packages(package, repos="http://cran.us.r-project.org")
    
  • 您可以将 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:

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

For multiple packages you can use

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

Pro tips:

  • When used inside the script, you can avoid a dialog screen by specifying the repos parameter of install.packages(), such as

    install.packages(package, repos="http://cran.us.r-project.org")
    
  • You can wrap require() and library() in suppressPackageStartupMessages() to, well, suppress package startup messages, and also use the parameters require(..., quietly=T, warn.conflicts=F) if needed to keep the installs quiet.

音盲 2024-11-07 08:13:59
?library

你会看到:

library(package)require(package) 都使用名称加载包
package 并将其放入搜索列表中。 require 专为使用而设计
其他函数内部;它返回 FALSE 并给出警告(而不是
如果包没有,则比 library() 默认情况下会出现错误)
存在。这两个函数都会检查并更新当前加载的列表
包,并且不要重新加载已经加载的包。 (如果你
想要重新加载这样的包,请调用 detach(unload = TRUE) 或
首先unloadNamespace。)如果你想加载一个包而不放置
如果它在搜索列表中,请使用 requireNamespace

?library

and you will see:

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.

长梦不多时 2024-11-07 08:13:59

我关于差异的最初理论是,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, while require 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.

離殇 2024-11-07 08:13:59

这似乎是已加载包的差异。
虽然 require 和library 确实都不会加载包。库在检查和退出之前会做很多其他事情。

我建议无论如何从运行 200 万次的函数的开头删除“require”,但如果出于某种原因我需要保留它。从技术上讲,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

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.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文