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

前端 未结 8 1105
情话喂你
情话喂你 2020-11-22 11:00

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

8条回答
  •  失恋的感觉
    2020-11-22 11:40

    Always use library. Never use require.

    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)

提交回复
热议问题