在没有矢量化FUN参数的情况下调用外部产品

ton*_*nov 2 r vectorization apply

我有一个d带向量参数的维度函数,我试图在一个简单的情况下在常规网格上计算它的值d=2.outer在这里尝试是很自然的,它可以很好地工作,即在简单的情况下

> outer(1:2, 3:4, function(x, y) x+y)
     [,1] [,2]
[1,]    4    5
[2,]    5    6
Run Code Online (Sandbox Code Playgroud)

但是,我的功能不支持自然矢量化.为了说明,想一​​想像

> outer(1:2, 3:4, function(x, y) length(c(x, y)))
Run Code Online (Sandbox Code Playgroud)

具有所需的输出(显然,上述代码的实际结果是错误)

     [,1] [,2]
[1,]    2    2
[2,]    2    2
Run Code Online (Sandbox Code Playgroud)

我当前的解决方法有点像apply(expand.grid(1:2, 3:4), 1, length),但对我来说这看起来有点笨拙.有没有像outer这种情况一样简单的事情?

ags*_*udy 6

使用以下方法"向量化"函数Vectorize:

outer(1:2, 3:4, Vectorize(function(x, y) length(c(x, y))))
     [,1] [,2]
[1,]    2    2
[2,]    2    2
Run Code Online (Sandbox Code Playgroud)

或者继续使用相同的想法expand.grid,但有mapply:

xx = expand.grid(1:2, 3:4)
mapply(function(x, y) length(c(x, y)), xx$Var1, xx$Var2)
[1] 2 2 2 2
Run Code Online (Sandbox Code Playgroud)

  • 你可以在任何地方附近"矢量化".这就像"它会混合吗?" :-) (2认同)