R library() and require() Functions - Loading Packages
The R library() function is used to load an installed extension package, making its functions available in the current session.
require() is similar, but returns FALSE instead of raising an error and stopping when the package does not exist.
The syntax of the two functions is as follows:
library(package)
require(package)
Parameter Description:
-
package The package name (quotes can be omitted).
Example
Load a built-in package (no installation needed)
library
(
stats
)
(
"stats package loaded"
)
View loaded packages
loaded
<-
search
(
)
(
"Currently loaded packages:"
)
(
loaded
[
1
:
5
]
)
Safe loading: require failure does not raise an error
if
(
require
(
"stats"
)
)
{
(
"stats package loaded successfully"
)
}
The difference between library and require
library("nonexistent_pkg") # Raises an error and stops execution
result
<-
require
(
"nonexistent_pkg"
)
Returns FALSE without stopping
(
paste
(
"Return value of require for a nonexistent package:"
, result
)
)
The output of the code above is:
[1] "stats 包已加载"
[1] "当前加载的包:"
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils"
[1] "stats 包加载成功"
[1] "不存在的包 require 返回: FALSE"
When writing scripts, it is recommended to use require() for safety checks: if a package does not exist, give a prompt instead of interrupting script execution.
R Language Examples