簡體   English   中英

R function `require` 在 `sapply` 中沒有按預期工作

[英]R function `require` does not work as expected in `sapply`

我想檢查是否正確安裝了一堆軟件包(使 dockerfile 崩潰而不是靜默繼續)。

我在 package 名稱的列表上嘗試了 sapply,結果就是這樣。 注意:

  • 'not_available' 未安裝:)
  • 'testthat' 已安裝。
# to show the invisible output:
> show <- function(x) {cat(x, '\n')}

> show(require('not_available'))
Loading required package: not_available
FALSE
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘not_available’

到目前為止一切順利,完全符合預期。

> show(require('testthat'))
TRUE

完美的...

> sapply(c('not_available', 'testthat'), require, warn.conflicts = FALSE, quietly = TRUE)
not_available      testthat 
        FALSE         FALSE 
Warning messages:
1: In if (!loaded) { :
  the condition has length > 1 and only the first element will be used
2: In if (!loaded) { :
  the condition has length > 1 and only the first element will be used

唔…

它為什么要警告我們? 為什么 output 不正確?

> sapply(c('not_available', 'testthat'), function(x) {x})
  not_available        testthat 
"not_available"      "testthat" 

好的,所以 sapply 沒有背叛我......

> sapply(c('not_available', 'testthat'), function(pkg) {require(pkg, warn.conflicts = FALSE, quietly = TRUE)})
not_available      testthat 
        FALSE         FALSE 

Eeeh,現在警告消失了,但答案......仍然是錯誤的......為什么?

有什么線索嗎? 預期行為將是帶有 [FALSE TRUE] 的返回值(與“not_available”和“testthat”相關)。

好吧,這是由於特殊的“庫”和“要求”行為也適用於未引用的值。 因此,以下將證明失敗:

pkgs <- 'testthat'
require(pkgs)
Loading required package: pkgs
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘pkgs’

解決方案是提供 'character.only'

sapply(c('not_available', 'testthat'), require, character.only = TRUE)
not_available      testthat 
        FALSE          TRUE

工作得很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM