library() vs require() in R

来源:互联网 发布:c罗官方数据 编辑:程序博客网 时间:2024/05/18 04:56

http://yihui.name/en/2014/07/library-vs-require/


While I was sitting in a conference room at UseR! 2014, I started counting the number of times that require() was used in the presentations, and would rant about it after I counted to ten. With drums rolling, David won this little award (sorry, I did not really mean this to you).

After I tweeted about it, some useRs seemed to be unhappy and asked me why. Bothrequire() and library() can load (strictly speaking, attach) an R package. Why should not one use require()? The answer is pretty simple. If you take a look at the source code ofrequire (use the source, Luke, as Martin Mächler mentioned in his invited talk), you will see that require() basically means “try to load the package using library() and return a logical value indicating the success or failure”. In other words, library() loads a package, andrequire() tries to load a package. So when you want to load a package, do you load a package or try to load a package? It should be crystal clear.

One bad consequence of require() is that if you require('foo') in the beginning of an R script, and use a function bar() in the foo package on line 175, R will throw an error object “bar” not found if foo was not installed. That is too late and sometimes difficult for other people to understand if they use your script but are not familiar with the foo package – they may ask, what is the bar object, and where is it from? When your code is going to fail, fail loudly, early, and with a relevant error message. require() does not signal an error, andlibrary() does.

Sometimes you do need require() to use a package conditionally (e.g. the sun is not going to explode without this package), in which case you may use an if statement, e.g.

if (require('foo')) {  awesome_foo_function()} else {  warning('You missed an awesome function')}

That should be what require() was designed for, but it is common to see R code like this as well:

if (!require('foo')) {  stop('The package foo was not installed')}

Sigh.

  • library('foo') stops when foo was not installed
  • require() is basically try(library())

Then if (!require('foo')) stop() is basically “if you failed to try to load this package, please fail”. I do not quite understand why it is worth the circle, except when one wants a different error message with the one from library(), otherwise one can simply load and fail.

There is one legitimate reason to use require(), though, and that is, “require is a verb and library is a noun!” I completely agree. require should have been a very nice name to choose for the purpose of loading a package, but unfortunately… you know.

If you take a look at the StackOverflow question on this, you will see a comment on “package vs library” was up-voted a lot of times. It used to make a lot of sense to me, but now I do not care as much as I did. There have been useRs (including me up to a certain point) desperately explaining the difference between the two terms package and library, but somehow I think R’s definition of a library is indeed unusual, and the function library() makes the situation worse. Now I’m totally fine if anyone calls my packages “libraries”, because I know what you mean.

Karthik Ram suggested this GIF to express “Ah a new library, but require? Noooooo”:

Since you have read the source code, Luke, you may have found that you can abuse require()a bit, for example:

> (require(c('MASS', 'nnet')))c("Loading required package: c", "Loading required package: MASS",  "Loading required package: nnet")Failed with error:  'package' must be of length 1In addition: Warning message:In if (!loaded) { :  the condition has length > 1 and only the first element will be used[1] FALSE> (require(c('MASS', 'nnet'), character.only = TRUE))c("Loading required package: MASS", "Loading required package: nnet")Failed with error:  'package' must be of length 1In addition: Warning message:In if (!loaded) { :  the condition has length > 1 and only the first element will be used[1] FALSE> library(c('MASS', 'nnet'), character.only = TRUE)Error in library(c("MASS", "nnet"), character.only = TRUE) :   'package' must be of length 1

So require() failed not because MASS and nnet did not exist, but because of a different error. As long as there is an error (no matter what it is), require() returns FALSE.

One thing off-topic while I’m talking about these two functions: the argumentcharacter.only = FALSE for library() and require() is a design mistake in my eyes. It seems the original author(s) wanted to be lazy to avoid typing the quotes around the package name, so library(foo) works like library("foo"). Once you show people they can be lazy, you can never pull them back. Apparently, the editors of JSS (Journal of Statistical Software) have been trying to promote the form library("foo") and discourage library(foo), but I do not think it makes much sense now or it will change anything. If it were in the 90’s, I’d wholeheartedly support it. It is simply way too late now. Yes, two extra quotation marks will kill many kittens on this planet. If you are familiar with *nix commands, this idea is not new – just think about tar -z -x -ftar -zxf, and tar zxf.

One last mildly annoying issue with require() is that it is noisy by default, because of the default quietly = FALSE, e.g.

> require('nnet')Loading required package: nnet> require('MASS', quietly = TRUE)

So when I tell you to load a package, you tell me you are loading a package, as if you had heard me. Oh thank you!

Yihui Xie / 2014-07-26 
Published under (CC) BY-NC-SA in categories R language  tagged with require  library 

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 电大本科文凭毕业证掉了怎么办 要求全日制本科自考本科怎么办 毕业证被学校扣了怎么办 自考本科档案没有密封怎么办 艺术生统考没过怎么办 本科科目没考过怎么办 军校体检条丢了怎么办 学美术考了大专怎么办 音基试唱音不准怎么办 音基证书丢了怎么办 职称计算机证书丢了怎么办 30岁了 开始怀旧怎么办 31岁了 缺乏运动怎么办 30多了还一事无成未来怎么办 导师说名额已满怎么办 在中国想当大官怎么办 站久了小腿变粗怎么办 苹果x锁屏延迟怎么办 被扇了巴掌耳痛怎么办 被扇了巴掌耳鸣怎么办 水兵舞不会扭胯怎么办 我的字写得很丑怎么办 二年级学生不会造句怎么办 w10下载种子文件失败怎么办 宝宝挂水手肿了怎么办 lol有英雄皮肤没英雄怎么办 qq聊天图标粉色钥匙怎么办 和舍友相处不来怎么办 被舍友偷了东西怎么办 体育生没过线怎么办 户主去世房产不能过户怎么办 苍蝇飞到嘴唇上怎么办 苍蝇不小心碰到嘴唇了怎么办 苍蝇老往身上飞怎么办 单位乒乓球比赛有领导参加怎么办 意外看到别人打野战怎么办 骨盆低想顺产要怎么办 右胯比左胯突出怎么办 一岁宝宝骨盆不对称怎么办 入盆了又出来了怎么办 大腿前突小腿后怎么办