关于使用outer()和用户定义函数的简单问题?

时间:2011-04-05 15:24:22

标签: r

> fun1 <- function(x,y){x+y}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun1)
     [,1] [,2] [,3] [,4] [,5]
[1,]    7    8    9   10   11
[2,]    8    9   10   11   12
[3,]    9   10   11   12   13
[4,]   10   11   12   13   14
[5,]   11   12   13   14   15
> fun2 <- function(x,y){z<-c(x,y);z[1]+z[2]}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun2)
Error in dim(robj) <- c(dX, dY) : 
  dims [product 25] do not match the length of object [1]

为什么fun2()不起作用?不是fun2()和fun1()本质上是一回事吗?

2 个答案:

答案 0 :(得分:15)

作为替代方案,您可以在将fun2作为参数传递给Vectorize(fun2)时将outer替换为fun2 <- function(x,y){z<-c(x,y);z[1]+z[2]} outer(seq(1,5,length=5),seq(6,10,length=5), Vectorize(fun2))

Day > Exercises > Sets

答案 1 :(得分:6)

如果您阅读?outer

,答案就会变得明显
Details:

     ‘X’ and ‘Y’ must be suitable arguments for ‘FUN’.  Each will be
     extended by ‘rep’ to length the products of the lengths of ‘X’ and
     ‘Y’ before ‘FUN’ is called.

     ‘FUN’ is called with these two extended vectors as arguments.
     Therefore, it must be a vectorized function (or the name of one),
     expecting at least two arguments.

想想你在做什么,你将两个向量连接成一个向量,然后对这个向量的第一个和第二个元素求和。另一方面,fun1()执行输入的矢量化和,因此返回的对象与输入的各个长度具有相同的长度。在fun2()中,输出是长度为1的向量,期望为25。

fun2()背后的理念是cbind() 而不是 c()两个输入:

> fun3 <- function(x, y) { z <- cbind(x, y); z[,1] + z[,2]}
> outer(seq(1,5,length=5),seq(6,10,length=5),fun3)
     [,1] [,2] [,3] [,4] [,5]
[1,]    7    8    9   10   11
[2,]    8    9   10   11   12
[3,]    9   10   11   12   13
[4,]   10   11   12   13   14
[5,]   11   12   13   14   15