define.bioregions<-function(tax.dist,geo.dist,method="average",plot=TRUE) { tax.tree<-hclust(tax.dist,method=method) geo.tree<-hclust(geo.dist,method=method) if(plot==T) { par(mfrow=c(1,2)) plot(tax.tree) plot(geo.tree) } geo.phylo<-as.phylo(geo.tree) tax.phylo<-as.phylo(tax.tree) geo.phylo$edge.length<-geo.phylo$edge.length*2 tax.subtrees<-subtrees(tax.phylo) tax.clusters<-vector(length=length(tax.subtrees),mode="list") for(i in 1:length(tax.clusters)) { tax.clusters[[i]]<-sort(tax.subtrees[[i]]$tip.label) } node.heights<-sort(dateNodes(geo.phylo),decreasing=F) test.node.heights<-node.heights[which(names(node.heights)%in%as.character(1:length(geo.phylo$tip.label))==F)] for(i in 1:geo.phylo$Nnode) { if(i==1) { level<-1 height.ranges<-vector(length=1,mode="list") height.ranges[[1]]<-vector(length=2) height.ranges[[1]][1]<-0 bioregions<-vector(length=1,mode="list") bioregions[[1]]<-1:length(geo.phylo$tip.label) names(bioregions[[1]])<-sort(geo.phylo$tip.label) } else { clust.node<-as.numeric(names(test.node.heights)[i-1]) children<-sort(geo.phylo$tip.label[Descendants(geo.phylo, clust.node, type ="tips")[[1]]]) for(j in 1:length(tax.clusters)) { if(identical(tax.clusters[[j]],children)==T) { level<-level+1 new.bioregions<-vector(length=level,mode="list") new.bioregions[1:length(bioregions)]<-bioregions new.bioregions[[level]]<-new.bioregions[[level-1]] change<-children[which(new.bioregions[[level]][children]!=new.bioregions[[level]][children[1]])] for(k in 1:length(change)) { new.bioregions[[level]][which(new.bioregions[[level]]>new.bioregions[[level]][change][k])]<-new.bioregions[[level]][which(new.bioregions[[level]]>new.bioregions[[level]][change][k])]-1 } new.bioregions[[level]][change]<-new.bioregions[[level]][children[1]] bioregions<-new.bioregions new.height.ranges<-vector(length=level,mode="list") new.height.ranges[1:length(height.ranges)]<-height.ranges new.height.ranges[[level]]<-vector(length=2) new.height.ranges[[level-1]][2]<-test.node.heights[i-1] new.height.ranges[[level]][1]<-test.node.heights[i-1] height.ranges<-new.height.ranges } } } } height.ranges[[length(height.ranges)]][2]<-max(test.node.heights) results<-list(bioregions,height.ranges) names(results)<-c("bioregions","height.ranges") return(results) }