需要()和库()之间的区别是什么?

时间:2022-01-11 13:20:38

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

需要()和库()之间的区别是什么?

8 个解决方案

#1


272  

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.

但是,根据两个函数的文档(通过put a访问)在函数名和命中输入之前,需要使用内部函数,因为它输出一个警告,如果没有找到包,则继续执行,而库将抛出一个错误。

#2


213  

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

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

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()。如果您想要将您的代码分发到我们的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")
    }
}

#3


52  

You can use require() if you want to install packages if and only if necessary, such as:

您可以使用require(),如果您想在必要时安装包,例如:

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.package()的repos参数来避免对话框。

    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.

    您可以将require()和库()打包到禁用的startupmessage()中,以抑制包启动消息,还可以使用参数要求(……如果需要的话,可以保持安静。

#4


41  

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.

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

在大多数其他情况下,最好使用library(),因为如果包不可用,这将在包加载时发出错误消息。如果包不在那里,则需要()只会失败。这是查找软件包是否需要安装的最佳时间(或者可能根本不存在,因为它拼写错误)。尽早获取错误反馈,并在相关的时间内避免可能的问题,因为在尝试使用库例程时,跟踪代码失败的原因。

#5


14  

?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.

库(包)和require(包)都将包和名称包装入到搜索列表中。要求设计用于其他功能;如果包不存在,它将返回FALSE并给出警告(而不是像库()默认设置的错误)。两个函数都检查和更新当前加载的包的列表,并且不重新加载已经加载的包。(如果您想重新加载这样的包,则首先调用detach(unload = TRUE)或unloadNamespace。)如果您希望加载一个包而不将其放在搜索列表中,则使用requireNamespace。

#6


8  

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.

我最初的理论不同的是,库加载包是否已经加载,即它可能会重新加载一个已经加载方案,同时需要检查它加载,或者加载它如果不是函数依赖(因此用一定的包)。但是,文档反驳了这一点,并且明确表示两个函数都不会重新加载已经加载的包。

#7


2  

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.

我建议从运行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

#8


-7  

require() loads all additional packages

要求()加载所有附加的包。

#1


272  

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.

但是,根据两个函数的文档(通过put a访问)在函数名和命中输入之前,需要使用内部函数,因为它输出一个警告,如果没有找到包,则继续执行,而库将抛出一个错误。

#2


213  

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

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

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()。如果您想要将您的代码分发到我们的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")
    }
}

#3


52  

You can use require() if you want to install packages if and only if necessary, such as:

您可以使用require(),如果您想在必要时安装包,例如:

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.package()的repos参数来避免对话框。

    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.

    您可以将require()和库()打包到禁用的startupmessage()中,以抑制包启动消息,还可以使用参数要求(……如果需要的话,可以保持安静。

#4


41  

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.

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

在大多数其他情况下,最好使用library(),因为如果包不可用,这将在包加载时发出错误消息。如果包不在那里,则需要()只会失败。这是查找软件包是否需要安装的最佳时间(或者可能根本不存在,因为它拼写错误)。尽早获取错误反馈,并在相关的时间内避免可能的问题,因为在尝试使用库例程时,跟踪代码失败的原因。

#5


14  

?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.

库(包)和require(包)都将包和名称包装入到搜索列表中。要求设计用于其他功能;如果包不存在,它将返回FALSE并给出警告(而不是像库()默认设置的错误)。两个函数都检查和更新当前加载的包的列表,并且不重新加载已经加载的包。(如果您想重新加载这样的包,则首先调用detach(unload = TRUE)或unloadNamespace。)如果您希望加载一个包而不将其放在搜索列表中,则使用requireNamespace。

#6


8  

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.

我最初的理论不同的是,库加载包是否已经加载,即它可能会重新加载一个已经加载方案,同时需要检查它加载,或者加载它如果不是函数依赖(因此用一定的包)。但是,文档反驳了这一点,并且明确表示两个函数都不会重新加载已经加载的包。

#7


2  

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.

我建议从运行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

#8


-7  

require() loads all additional packages

要求()加载所有附加的包。