Jeason
292字小于1分钟
2018-02-08
在R语言中,载入R包函数有两个:library()
和 require()
,但是两者之间又存在很大的不同
library()
会提示Error,并且停止运行;执行 require()
会提示Warning,继续执行运算library("abc")
Error in library("abc") : there is no package called 'abc'
require("abc")
## Loading required package: abc
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
## there is no package called 'abc'
library()
只停止运算,只会显示错误提示,没有返回值;require()
会返回一个逻辑值test <- library("abc")
Error in library("abc") : there is no package called 'abc
test #显示错误提示
Error: object 'test' not found
test <- require("abc")
## Loading required package: abc
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
## there is no package called 'abc'
test
## [1] FALSE
在自定义函数中,可以利用 require()
函数来检测运行环境,确保函数可以正确运行
if(require("MASS")){
print("MASS is loaded correctly")
} else {
print("you need install MASS package")
install.packages("MASS")
if(require(MASS)){
print("MASS installed and loaded")
} else {
stop("could not install MASS")
}
}