[R] converting similarity matrix formats

Gabor Csardi csardi at rmki.kfki.hu
Sun Apr 23 07:42:23 CEST 2006


Let S be your input matrix and M your output.

name <- unique(c(S[,1],S[,2]))
M <- matrix(1, nr=length(name), nc=length(name), dimnames=list(name, name))
apply(S, 1, function(r) M[r[1],r[2]] <<- M[r[2],r[1]] <<- as.numeric(r[3])) 

You might want to put it into a function.....

Gabor


On Sun, Apr 23, 2006 at 12:24:32AM -0500, Lex Flagel wrote:
> Dear all,
> I am using a program that generates similarity matrices in the following
> non-redundant pairwise format.
> 
> a  b  0.4
> a  c  0.5
> a  d  0.3
> b  c  0.9
> b  d  0.6
> c  d  0.2
> 
> matrix(c('a','a','a','b','b','c','b','c','d','c','d','d',.4,.5,.3,.9,.6,.2),byrow=F,nrow=6)
> 
> I would like to convert this to a full similarity matrix of the following
> format.
> 
>       a      b     c     d
> a    1     .4    .5    .3
> b    .4     1    .9    .6
> c    .5    .9     1    .2
> d    .3    .6    .2     1
> 
> Additionally, I need to be able to apply this conversion to many data sets
> with a different dimensions, so a generalized approach would be preferred.
> 
> Thanks for any advice, I'm stuck!
> Lex
> 
> --
> Lex Flagel
> 
> Interdepartmental Genetics Program,
> Department of Ecology, Evolution, and Organismal Biology,
> Iowa State University,
> Mail: 251 Bessey Hall,
> Office: 353 Bessey Hall,
> Lab: 431 Bessey Hall,
> Ames, IA 50011
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

-- 
Csardi Gabor <csardi at rmki.kfki.hu>    MTA RMKI, ELTE TTK




More information about the R-help mailing list