Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R library() and require() Functions - Loading Packages

R library() and require() Functions - Loading Packages

R Language Examples R Language Examples

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:

Example

Load a 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 failure does not raise an error

if

(

require

(

"stats"

)

)

{

 

print

(

"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

print

(

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 R Language Examples