What is the difference between require() and library()?
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
What is the difference between library()/require() and source() in r?
The differences between library
and require
are already well documented in What is the difference between require() and library()?.
So, I will focus on how source
differs from these. In fact they are fundamentally quite different commands. Neither library
nor require
actually execute any code. They simply attach a namespace, in a lazy fashion, meaning that individual functions in the package are not run unless they are actually called later. Source on the other hand does something quite different which is to execute all of the code in the file at that time.
A small caveat: packages can be made to actually run some code at the time of package loading or attaching, via the .onLoad
and .onAttach
functions. Have a look here: https://stat.ethz.ch/R-manual/R-devel/library/base/html/ns-hooks.html
Why library() or require() should not be used in a R package
You should never use library()
or require()
in a package, because they affect the user's search list, possibly causing errors for the user.
For example, both the dplyr
and stats
packages export a function called filter
. If a user had only library(stats)
, then filter
would mean stats::filter
, but if your package called library(dplyr)
, the user might suddenly find that filter
means dplyr::filter
, and things would break.
There are a couple of alternatives for your package. You can import functions from another package by listing it in the Imports:
field in the DESCRIPTION
file and specifying the imports in the NAMESPACE
file. (The roxygen2
package can make these changes for you automatically if you put appropriate comments in your .R
source files, e.g.
#' @importFrom jsonlite toJSON unbox
before a function that uses those to import toJSON()
and unbox()
from the jsonlite
package.)
The other way to do it is using the ::
notation. Then you can still list a package in the Imports:
field of DESCRIPTION
, but use code like
jsonlite::toJSON(...)
every time you want to call it. Alternatively, if you don't want a strong dependence on jsonlite
, you can put jsonlite
in Suggests:
, and wrap any uses of it in code like
if (requireNamespace("jsonlite")) {
jsonlite::toJSON(...)
}
Then people who don't have that package will still be able to run your function, but it may skip some operations that require jsonlite
.
R writing style - require vs. ::
"Why should one prefer require over ::
when writing a function?"
I usually prefer require
due to the nice TRUE/FALSE return value that lets me deal with the possibility of the package not being available up front before getting into the code. Crash as early as possible instead of halfway through your analysis.
I only use ::
when I need to make sure I am using the correct version of a function, not a version from some other package that is masking the name.
On the other hand, :: operator gets
the variable from the package, while
require loads whole package (at least
I hope so), so speed differences came
first to my mind. :: must be faster
than require.
I think you may be ignoring the effects of lazy loading which is used by the foreign
package according to the first page of its manual. Essentially, packages that use lazy loading defer the loading of objects, such as functions, until the objects are called upon for the first time. So your argument that "::
must be faster than require" is not necessarily true as foreign
is not loading all of its contents into memory when you attach it with require
. For full details on lazy loading, see Prof. Ripley's article in RNews, Volume 4, Issue 2.
What is the difference between include and require in Ruby?
What's the difference between
"include" and "require" in Ruby?Answer:
The include and require methods do
very different things.The require method does what include
does in most other programming
languages: run another file. It also
tracks what you've required in the
past and won't require the same file
twice. To run another file without
this added functionality, you can use
the load method.The include method takes all the
methods from another module and
includes them into the current module.
This is a language-level thing as
opposed to a file-level thing as with
require. The include method is the
primary way to "extend" classes with
other modules (usually referred to as
mix-ins). For example, if your class
defines the method "each", you can
include the mixin module Enumerable
and it can act as a collection. This
can be confusing as the include verb
is used very differently in other
languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require
.
Oddly enough, Ruby's require
is analogous to C's include
, while Ruby's include
is almost nothing like C's include
.
Difference between require, include, require_once and include_once?
There are require
and include_once
as well.
So your question should be...
- When should I use
require
vs.include
? - When should I use
require_once
vs.require
The answer to 1 is described here.
The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
The answer to 2 can be found here.
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
The difference between require(x) and import x
This simple diagram will help you understand the difference between require
and import
.
Apart from that,
You can't selectively load only the pieces you need with require
but with import
, you can selectively load only the pieces you need, which can save memory.
Loading is synchronous(step by step) for require
on the other hand import
can be asynchronous(without waiting for previous import) so it can perform a little better than require
.
install_version breaks symlinks in the renv library
I found the problem with my approach. Instead of using install_version
, I should have used renv::install()
. Here is an example:
Instead of using:
devtools::install_version(package="BART", version = "2.2")
Use
renv::install("BART")
renv::install("BART@2.2")
Related Topics
Find All Combinations of a Set of Numbers That Add Up to a Certain Total
R: Error in Usemethod("Tbl_Vars")
How to Dplyr Rename a Column, by Column Index
Delete Rows Containing Specific Strings in R
Creating Grouped Bar-Plot of Multi-Column Data in R
How to Convert a Data Frame Column to Numeric Type
Break Dataframe into Smaller Dataframe'S and Save Them
How to Replace Negative Values in a Dataframe Column With a Different Value
Conditionally Remove Rows from a Database Using R
Adding Some Space Between the X-Axis and the Bars, in Ggplot
Convert Categorical Variables to Numeric in R
How to Select Variables in an R Dataframe Whose Names Contain a Particular String
How to Add a Diagonal Line to a Plot
Gsub a Every Element After a Keyword in R
Change the Class from Factor to Numeric of Many Columns in a Data Frame
Convert Dataframe Column to 1 or 0 for "True"/"False" Values and Assign to Dataframe