R library() and require() functions - Loading packages
The R library() function is used to load installed extension packages, making their functions available for the current session.
require() is similar, but returns FALSE when the package does not exist instead of raising an error and terminating.
The syntax format of the two functions is as follows:
library(package) require(package)
Parameter description:
packagePackage name (quotes can be omitted).
Examples
# Load built-in package (no installation needed)
library(stats)
print("stats package loaded")
# View loaded packages
loaded <- search()
print("Currently loaded packages:")
print(loaded[1:5])
# Safe loading: require does not raise an error on failure
if (require("stats")) {
print("stats package loaded successfully")
}
# Difference between library and require
# library("nonexistent_pkg") # will raise an error and stop execution
result <- require("nonexistent_pkg") # returns FALSE, does not stop
print(paste("For a nonexistent package, require returns:", result))
library(stats)
print("stats package loaded")
# View loaded packages
loaded <- search()
print("Currently loaded packages:")
print(loaded[1:5])
# Safe loading: require does not raise an error on failure
if (require("stats")) {
print("stats package loaded successfully")
}
# Difference between library and require
# library("nonexistent_pkg") # will raise an error and stop execution
result <- require("nonexistent_pkg") # returns FALSE, does not stop
print(paste("For a nonexistent package, require returns:", result))
Executing the above code produces the following output:
[1] "stats 包已加载" [1] "当前加载的包:" [1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" [1] "stats 包加载成功" [1] "不存在的包 require 返回: FALSE"
Other extensionsWhen writing scripts, it is recommended to use require() for safety checks: if a package does not exist, show a prompt rather than interrupting script execution.
R Language Examples