[R] `bivariate apply'
Gabor Grothendieck
ggrothendieck at myway.com
Tue Dec 16 17:34:06 CET 2003
The following:
- uses apply to turn the input matrix, x, into a vector of lists,
each of which represents one column
- this vector of lists is replicated two different ways and
- mapply is used on the replicated structures.
- finally, reform the result into a matrix
This solution has the property that it does not deal with indices
at all.
biapply <- function(x,f=cor) {
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 )
}
# test
x <- matrix( 1:12, 4, 3 )
biapply( x, crossprod )
biapply( x )
---
Date: Tue, 16 Dec 2003 14:13:29 +0100
From: Vito Muggeo <vito.muggeo at giustizia.it>
To: <r-help at stat.math.ethz.ch>
Subject: [R] `bivariate apply'
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
More information about the R-help
mailing list