R: [R] `bivariate apply' - Summary

Vito Muggeo vito.muggeo at giustizia.it
Thu Dec 18 12:31:34 CET 2003


Dear all,
Thanks to Thomas Lumley, Peter Wolf and Gabor Grothendieck for their reply

The problem was to to apply a bivariate function (such as cor(), for
instance) to each combination of colums of a given matrix.

Below there are four possible solutions (the original message is also posted
below). Using a matrix 5000x20, the best solutions seem to be f1 and f2.


f1<-function(mat, FUN, ...){
#author: Thomas Lumley
    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)
}

f2<-function(x,fun=cor){
#author: Peter Wolf
 cl<-matrix(1:ncol(x),ncol(x),ncol(x))
 cl<-cbind(as.vector(cl),as.vector(t(cl)))
 res<-apply(cl,1,function(xx)fun(x[,xx[1]],x[,xx[2]]))
 matrix(res,ncol(x),ncol(x))
}

f3 <- function(x,f=cor) {
#author: Gabor Grothendieck
   k <- NCOL( x )
   x <- apply( x, 2, list )
   ff <- function(x,y) f( unlist(x), unlist(y) )
   matrix( mapply( ff, rep(x,rep(k,k)), rep(x,k) ), k, k )
}

f4<-function(x,FUN,...){
#author: vito muggeo
    require(gregmisc)
    a<-combinations(ncol(x),2)
    r<-list()
    for(i in 1:nrow(a)){r[[length(r)+1]]<- x[,a[i,]]}
    ris<-matrix(1,ncol(x),ncol(x))
    ris1<-sapply(r, function(xx)FUN(xx[,1],xx[,2],...))
    ris[col(ris)<row(ris)]<- ris[col(ris)>row(ris)]<-ris1
    return(ris)
    }


# test
x <- matrix( runif(5000*20), 5000, 20 )
system.time(f1( x, cor ))



##original message
 > 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
>
> Can anybody help me?
>
> many thanks in advance,
> vito
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Introducing My Way - http://www.myway.com




More information about the R-help mailing list