由@hadley 的提示 article on functionals referenced in an answer today ,我决定重新审视一个关于 outer
的持久谜题。函数有效(或无效)。为什么会失败:
outer(0:5, 0:6, sum) # while outer(0:5, 0:6, "+") succeeds
这说明了我的想法
outer
应该处理类似 sum
的函数: Outer <- function(x,y,fun) {
mat <- matrix(NA, length(x), length(y))
for (i in seq_along(x)) {
for (j in seq_along(y)) {mat[i,j] <- fun(x[i],y[j])} }
mat}
> Outer(0:5, 0:6, `+`)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0 1 2 3 4 5 6
[2,] 1 2 3 4 5 6 7
[3,] 2 3 4 5 6 7 8
[4,] 3 4 5 6 7 8 9
[5,] 4 5 6 7 8 9 10
[6,] 5 6 7 8 9 10 11
好的,我的索引没有与该示例完全对齐,但修复起来并不难。问题是为什么像
sum
这样的函数应该能够接受两个参数并返回适合矩阵元素的(原子)值,但在传递给 base::outer
时不能这样做功能?所以@agstudy 为
Outer
的更紧凑版本提供了灵感。他的更紧凑: Outer <- function(x,y,fun) {
mat <- matrix(mapply(fun, rep(x, length(y)),
rep(y, each=length(x))),
length(x), length(y))
然而,问题仍然存在。术语“矢量化”在这里有些含糊,我认为“二元”更正确,因为
sin
和 cos
是术语通常意义上的“矢量化”。期待 outer
是否存在基本的逻辑障碍?以可以使用非二元函数的方式扩展其参数。这是另一个
outer
-错误可能与我对这个问题缺乏了解有关:> Vectorize(sum)
function (..., na.rm = FALSE) .Primitive("sum")
> outer(0:5, 0:6, function(x,y) Vectorize(sum)(x,y) )
Error in outer(0:5, 0:6, function(x, y) Vectorize(sum)(x, y)) :
dims [product 42] do not match the length of object [1]
最佳答案
outer(0:5, 0:6, sum)
不工作,因为 sum
未“向量化”(在返回与其两个参数长度相同的向量的意义上)。这个例子应该解释了不同之处:
sum(1:2,2:3)
8
1:2 + 2:3
[1] 3 5
您可以矢量化
sum
使用 mapply
例如:identical(outer(0:5, 0:6, function(x,y)mapply(sum,x,y)),
outer(0:5, 0:6,'+'))
TRUE
PS:一般使用前
outer
我用 browser
在 Debug模式下创建我的函数:outer(0:2, 1:3, function(x,y)browser())
Called from: FUN(X, Y, ...)
Browse[1]> x
[1] 0 1 2 0 1 2 0 1 2
Browse[1]> y
[1] 1 1 1 2 2 2 3 3 3
Browse[1]> sum(x,y)
[1] 27 ## this give an error
Browse[1]> x+y
[1] 1 2 3 2 3 4 3 4 5 ## this is vectorized
关于r - 为什么外部工作不像我认为的那样(在 R 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110397/