【问题标题】:How to pass arguments to function called from mapply directly OR how to treat vector as argument to function not to mapply如何将参数传递给直接从 mapply 调用的函数,或者如何将向量作为函数的参数而不是 mapply
【发布时间】:2016-04-05 08:59:23
【问题描述】:

假设我有以下功能:

my.fun1 <- function(a,b,c){
  a * c + b
}

如果我想用多个参数多次调用它,我可以这样做:

> my.fun1(1, 1, c(1:3))
[1] 2 3 4
> my.fun1(2, 2, c(1:3))
[1] 4 6 8
> my.fun1(3, 3, c(1:3))
[1]  6  9 12

但如果我使用 mapply 我会得到这个:

> mapply(my.fun1, c(1:3), c(1:3), c(1:3))
[1]  2  6 12

而不是想要的:

[[1]]
[1] 2 3 4

[[2]]
[1] 4 6 8

[[3]]
[1]  6  9 12

恕我直言,问题在于mapply 基本上将函数调用转换为:

> my.fun1(1, 1, 1)
[1] 2
> 
> my.fun1(2, 2, 2)
[1] 6
> 
> my.fun1(3, 3, 3)
[1] 12

如何将mapply 的最后一个参数直接传递给my.fun1,而不被视为mapply 的参数,而是传递给my.func1

PS:我一直在 maplpy 调用中使用匿名函数。最接近的是get(基于建议here):

> x <- mapply(function(x, y){my.fun1(x, y, c(1:3))}, c(1:3), c(1:3))
> split(x, rep(1:ncol(x), each = nrow(x)))
$`1`
[1] 2 3 4

$`2`
[1] 4 6 8

$`3`
[1]  6  9 12

但我想这是丑陋的方法,必须有更好的方法。

【问题讨论】:

    标签: r mapply


    【解决方案1】:

    由于my.fun1 中的最后一个输入与vector 相同,我们将其放在list 中并将其作为Mapmapply 的参数传递。

    Map(my.fun1, 1:3, 1:3, list(1:3))
    

    或者正如@baptiste 提到的,可以使用MoreArgs 传递常量

    Map(my.fun1, 1:3, 1:3, MoreArgs = list(c=1:3))
    

    当我们使用mapply时,最好有SIMPLIFY=FALSE以避免将list强制转换为matrix(如果list元素的长度相同的话。

    mapply(my.fun1, 1:3, 1:3, list(1:3), SIMPLIFY=FALSE)
    

    【讨论】:

    • 我通常会将常量传递为MoreArgs=list(c=1:3)
    • @谢谢。我看到在这两种情况下(Mapmapply)都使用了将向量转换为列表。为什么以这种方式工作,列表传递给函数的方式与向量不同,或者有什么诀窍?
    • @WakanTanka Mapmapply 的一个方便函数。如果您检查Map 函数,它只是mapply(FUN = f, ..., SIMPLIFY = FALSE)。关于list 的工作方式不同,只是list 中只有一个元素。因此,它为向量的每个对应元素回收了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2013-12-08
    • 2022-01-17
    • 2021-06-11
    相关资源
    最近更新 更多