【问题标题】:How to specify which arguments to be iterated in mapply in R如何在 R 中的 mapply 中指定要迭代的参数
【发布时间】:2016-09-23 12:48:07
【问题描述】:

我是 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 函数)而不必为同一件事创建很多副本?

感谢您的建议。

【问题讨论】:

    标签: r apply lapply sapply mapply


    【解决方案1】:

    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))
    

    【讨论】:

    • 正是这个。谢谢
    【解决方案2】:

    一种方法是使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2020-07-28
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 2015-05-29
      相关资源
      最近更新 更多