Tuesday, March 8, 2016

Simple function to match labels between trees

As part of something else that I'm working on I wanted to match labels between two trees in a manner analagous to the phytools function matchNodes (that is, a matrix with the corresponding node indices for the two trees, if nodes could be matched, and NA otherwise).

Here is what that very simple function looks like:

matchLabels<-function(tr1,tr2){
    foo<-function(x,y) if(length(obj<-which(y==x))>0) obj else NA
    M<-cbind(1:Ntip(tr1),sapply(tr1$tip.label,foo,y=tr2$tip.label))
    colnames(M)<-c("tr1","tr2")
    M
}

Here is how it works:

library(phytools)
t1<-rtree(n=14)
t2<-rtree(n=10)
par(mfrow=c(1,2))
plotTree(t1,offset=0.6)
tiplabels()
plotTree(t2,offset=0.6)
tiplabels()

plot of chunk unnamed-chunk-2

matchLabels(t1,t2)
##     tr1 tr2
## t14   1  NA
## t8    2   3
## t1    3   4
## t6    4   7
## t11   5  NA
## t3    6   6
## t5    7   2
## t2    8  10
## t7    9   5
## t9   10   8
## t13  11  NA
## t10  12   9
## t4   13   1
## t12  14  NA
matchLabels(t2,t1)
##     tr1 tr2
## t4    1  13
## t5    2   7
## t8    3   2
## t1    4   3
## t7    5   9
## t3    6   6
## t6    7   4
## t9    8  10
## t10   9  12
## t2   10   8

Or, equivalently:

obj<-cophylo(t1,t2,rotate=FALSE)
plot(obj)
tiplabels.cophylo(which="left")
tiplabels.cophylo(which="right")

plot of chunk unnamed-chunk-3

That's all there is to it.

No comments:

Post a Comment

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.