[R] Apply function to do pairwise calculation

arun smartpink111 at yahoo.com
Tue Oct 1 05:20:27 CEST 2013


Hi,
Not sure if this helps.

#example dataset
set.seed(24)
 mat1<-matrix(sample(1:50,20*20,replace=TRUE),ncol=20)
  set.seed(49)
 colnames(mat1)<- sample(rep(LETTERS[1:4],5),20)
 rownames(mat1)<- colnames(mat1)

mat2<-combn(LETTERS[1:4],2)
res<- sapply(split(mat2,col(mat2)),function(x){ x1<-mat1[rownames(mat1)%in% x[1],colnames(mat1)%in%x[1]]; x2<- mat1[rownames(mat1)%in% x[2],colnames(mat1)%in% x[2]];avecor(x1,x2)})
names(res)<- apply(mat2,2,paste,collapse="")
res
#       AB        AC        AD        BC        BD        CD 
#0.4806725 0.4505996 0.6160342 0.5567617 0.3721136 0.4480448 

A.K.




----- Original Message -----
From: Amanda Li <amandali at uchicago.edu>
To: r-help at r-project.org
Cc: 
Sent: Monday, September 30, 2013 10:55 AM
Subject: [R] Apply function to do pairwise calculation

Hello,

I want to do pairwise calculation, but I am not sure how to do so.

i.e. I have a correlation matrix M 200*200. Namely colnames(M)=rownames(M).
In addition, colnames(M) is one of A, B, C, D. I want to first sort the
matrix M into 16 modules according to colnames and rownames, and then apply:
avecor <- function(x,y) {
z <- (sum(cor(x,y)*cor(x,y))/length(cor(x,y)))^0.5
return(z)
}

So as to calculate the average correlation between A,B; A,C; A,D; B,C; B,D;
C,D.

Thanks in advance for your help!

Best,
Amanda

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list