Vectorize return 如何无形中得到结果?

How to get Vectorize return the results invisibly?

我有一个绘图函数 f 不应该 return 任何输出。

f <- function(a=0) invisible(NULL)
f(10)

向量化 f 之后,它 return NULL

f_vec <- Vectorize(f)
f_vec(10)
[[1]]
NULL

我怎样才能防止这种情况发生,即在这里也使输出不可见。 我当然可以使用包装器来抑制它。

f_wrapper <- function(a=0) {
  dummy <- f_vec(a)
}
f_wrapper(10)

有没有办法避免包装并立即得到我想要的东西?

是的。这个新版本的 Vectorize 可以做到:

Vectorize_2 <- function (FUN, vectorize.args = arg.names, SIMPLIFY = TRUE, USE.NAMES = TRUE) {
  arg.names <- as.list(formals(FUN))
  arg.names[["..."]] <- NULL
  arg.names <- names(arg.names)
  vectorize.args <- as.character(vectorize.args)
  if (!length(vectorize.args)) 
    return(FUN)
  if (!all(vectorize.args %in% arg.names)) 
    stop("must specify names of formal arguments for 'vectorize'")
  FUNV <- function() {
    args <- lapply(as.list(match.call())[-1L], eval, parent.frame())
    names <- if (is.null(names(args))) 
      character(length(args))
    else names(args)
    dovec <- names %in% vectorize.args
    invisible(do.call("mapply", c(FUN = FUN, args[dovec], MoreArgs = list(args[!dovec]), 
                                  SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES)))
  }
  formals(FUNV) <- formals(FUN)
  FUNV
}

但是,我怎么知道要这样做的?我是否花了 20 分钟写了 Vectorize 的 b运行d 新版本?不!我只是 运行 dput(Vectorize) 查看 Vectorize 后面的 R 代码,并在必要时添加了 invisible !您可以使用所有 R 函数执行此操作。您甚至不需要 dput!就 运行 Vectorize!