我已经矢量化了一个自定义函数,为什么 outer 给我一个错误?

I've vectorized a custom function, why is outer giving me an error?

  cubeAndAdd<-function(x,y){x^3+y^3}
  outer(-1:1,-1:1,function(x,y) Vectorize(cubeAndAdd(x,y)))

在 运行 执行此操作后,您将收到警告消息:

Warning message:
In formals(fun) : argument is not a function

这是为什么?毕竟,如果我真的没有使用函数,那么这段代码根本不会 运行。

问题出在您 'feeding' 到 Vectorize 之间。

Vectorize 想要一个函数作为它的参数。 cubeAndAdd是一个函数,但是cubeAndAdd(x,y)是一个函数call

为了使您的 outer 循环语法正确,您应该使用 Vectorize 创建向量化函数,然后调用该新函数:

outer(-1:1,-1:1,function(x,y) Vectorize(cubeAndAdd)(x,y))

此处,Vectorize(cubeAndAdd) 是函数,您使用 (x,y) 作为参数调用它:所以 Vectorize(cubeAndAdd)(x,y)

(尽管从 outer 循环中删除整个匿名 function(x,y) 的建议在这里有效(并使单行代码更短),但显式 [=34 通常是个好主意=] 函数的参数,就像你正在做的那样,因为这允许一个人使用需要额外参数的函数)。