如何指定要在 R 中的 mapply 中迭代的参数

How to specify which arguments to be iterated in mapply in R

我是 R 的新手,因此我是应用函数的新手。我还没有在任何地方找到这个问题的答案,尽管我有一个(不太优雅的)解决它的方法。

考虑这个虚拟代码:

my.fun <- function(vector1, vector2, vector3 = NULL) {
    # do stuff with the vectors
}

list1 <- mapply(FUN = my.fun, arg1, arg2, list(arg3), SIMPLIFY = FALSE)

假设 arg1 和 arg2 是我想在 mapply 函数内迭代的列表(长度相同),但 arg3 只是我想在 my.fun() 中使用而不被迭代的向量。我的问题是:如何在所有 mapply 函数迭代中将 arg3 置于 my.fun() 中?澄清一下,my.fun() 中的 vector3 应该等于 my.fun() 之外的 arg3。

一种方法是:

list1 <- mapply(FUN = my.fun, arg1, arg2, rep(list(arg3), length(arg1)), SIMPLIFY = FALSE)

但看起来应该有更优雅的方式。

有没有一种方法可以指定迭代哪些参数,哪些不迭代?或者做同样的事情(使用 apply-family 函数)而不必创建相同事情的大量副本?

感谢您的任何建议。

一种方法是使用 Map 函数和匿名函数。这是一个例子

myFunction <- function(arg1, arg2, arg3) {
  arg1 + arg2 + arg3
}

arg1 <- 1:5
arg2 <- 5:1
arg3 <- 1

Map(function(arg1, arg2) myFunction(arg1, arg2, arg3=arg3), arg1, arg2)

mapply() 有一个 MoreArgs= 参数用于此目的。

例如:

par(mfcol=c(2,2), ann=FALSE, mar=c(1,1,1,1))
mapply(plot, x=1:4, y=4:1, col=1:4,
       MoreArgs=list(xlim=c(1,4), ylim=c(1,4), pch=16, cex=3))