Hi Liam and David,

Thanks for the code! It will be very useful for the trees I'm working with. Two 
clades are large, and I need to collapse them for diversitree.

Best,

John

John S. S. Denton
Ph.D. Candidate
Department of Ichthyology and Richard Gilder Graduate School
American Museum of Natural History
www.johnssdenton.com
________________________________________
From: Liam J. Revell [liam.rev...@umb.edu]
Sent: Saturday, June 22, 2013 8:09 AM
To: John Denton
Cc: David Bapst; r-sig-phylo@r-project.org
Subject: Re: [R-sig-phylo] collapse descendants of a node to a polytomy

Hi John.

Here is an alternative to David's second solution that also retains the
branch lengths everywhere else in the tree & the height above the root
for the tips in the star subtree. It uses phytools (and its dependencies).

collapse.to.star<-function(tree,node){
tt<-splitTree(tree,split=list(node=node,bp=tree$edge.length[which(tree$edge[,2]==node)]))
ss<-starTree(species=tt[[2]]$tip.label,branch.lengths=diag(vcv(tt[[2]])))
ss$root.edge<-0
tree<-paste.tree(tt[[1]],ss)
return(tree)
}

# e.g.,
library(phytools)
set.seed(1)
tree<-pbtree(n=30)
plotTree(tree,node.numbers=T)
node<-fastMRCA(tree,"t15","t5")
tree2<-collapse.to.star(tree,node)
plotTree(tree2)


Liam J. Revell, Assistant Professor of Biology
University of Massachusetts Boston
web: http://faculty.umb.edu/liam.revell/
email: liam.rev...@umb.edu
blog: http://blog.phytools.org

On 6/22/2013 5:21 AM, David Bapst wrote:
> library(ape)
> set.seed(444)
> tree<-rtree(10)
> plot(tree)
> node<-mrca(tree)["t4","t2"]
>
> #collapse immediate branches
> tree1<-tree
> tree1$edge.length<-rep(1,
> Nedge(tree1))    #replace all edge lengths with 1
> tree1$edge.length[tree1$edge[,1]==node]<-0    #replace descendent edge
> lengths with 0
> tree1<-di2multi(tree1)
> tree1$edge.length<-NULL    #get rid of branch lengths
>
> plot(tree1)
>
> #collapse all descendant branches
> tree2<-tree
> library(phangorn)
> descNodes<-Descendants(tree2,node,"all")
> tree2$edge.length<-rep(1,Nedge(tree2))    #replace all edge lengths with 1
> descEdges<-sapply(tree2$edge[,2],function(x) any(x==descNodes))
> tree2$edge.length[descEdges]<-0
> tree2<-di2multi(tree2)
> tree2$edge.length<-NULL    #get rid of branch lengths
>
> plot(tree2)

_______________________________________________
R-sig-phylo mailing list - R-sig-phylo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-phylo
Searchable archive at http://www.mail-archive.com/r-sig-phylo@r-project.org/

Reply via email to