我有一个带有向量参数的 d
维函数,我试图在一个简单的情况下计算其在规则网格上的值 d=2
。在这里尝试 outer
是很自然的,它工作得很好,即在简单的情况下
> outer(1:2, 3:4, function(x, y) x+y)
[,1] [,2]
[1,] 4 5
[2,] 5 6
但是,我的函数不支持自然向量化。为了说明这一点,想想像
> outer(1:2, 3:4, function(x, y) length(c(x, y)))
具有期望的输出(显然,上述代码的实际结果是错误的)
[,1] [,2]
[1,] 2 2
[2,] 2 2
我目前的解决方法与 apply(expand.grid(1:2, 3:4), 1, length)
类似,但我觉得这有点笨拙。对于这种情况,有没有像 outer
这样简单的东西?
最佳答案
或者你使用Vectorize
“向量化”你的函数:
outer(1:2, 3:4, Vectorize(function(x, y) length(c(x, y))))
[,1] [,2]
[1,] 2 2
[2,] 2 2
或者使用 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
关于r - 在没有矢量化 FUN 参数的情况下调用外积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21628704/