[R] `bivariate apply'

Thomas Lumley tlumley at u.washington.edu
Tue Dec 16 15:24:00 CET 2003


On Tue, 16 Dec 2003, Vito Muggeo wrote:

> dear all,
>
> Given a matrix A, say, I would like to apply a bivariate function to each
> combination of its colums. That is if
>
> myfun<-function(x,y)cor(x,y) #computes simple correlation of two vectors x
> and y
>
> then the results should be something similar to cor(A).
>
> I tried with mapply, outer,...but without success
>

I don't think there's anything better than a simple loop.   If you insist
on making the loops invisible you could do eg:

pwapply<-function(mat, FUN, ...){
	nc<-NCOL(mat)
	i<-rep(1:nc, nc)
 	j<-rep(1:nc, each=nc)
	rval<-mapply(function(ii,ji) FUN(mat[,ii], mat[,ji], ...), i, j)
	matrix(rval, nc=nc)
}



	-thomas




More information about the R-help mailing list