[R] `bivariate apply'
Peter Wolf
s-plus at wiwi.uni-bielefeld.de
Tue Dec 16 15:45:00 CET 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
>
>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
>
>
what about
myfun<-function(x,fun=cor){
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))
}
Peter Wolf
More information about the R-help
mailing list