3 回答

TA貢獻2037條經驗 獲得超6個贊
日常工作中沒有多少人。
但是,根據兩個函數的文檔(通過?
在函數名稱之前輸入并按下enter鍵訪問),require
在函數內部使用,因為它輸出警告并在未找到包時繼續,但library
會拋出錯誤。

TA貢獻1884條經驗 獲得超4個贊
另一個好處require()是它默認返回一個邏輯值。TRUE如果包是加載的,FALSE如果不是。
> 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 message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called 'abc'
> test
[1] FALSE
所以你可以使用require()像下面這樣的結構。如果您想將代碼分發到我們的R安裝,那么主要方便的是可能沒有安裝軟件包。
if(require("lme4")){
print("lme4 is loaded correctly")
} else {
print("trying to install lme4")
install.packages("lme4")
if(require(lme4)){
print("lme4 installed and loaded")
} else {
stop("could not install lme4")
}
}
- 3 回答
- 0 關注
- 1156 瀏覽
添加回答
舉報