# [R-sig-phylo] midpoint rooting?

Klaus Schliep klaus.schliep at gmail.com
Thu Sep 2 18:17:59 CEST 2010

```Dear Robin,

here is a function, that does midpoint rooting, you have to attach the
phangorn package. It is likely to appear in one of the next ape
versions.

Cheers,
Klaus

midpoint <- function(tree){
dm = cophenetic(tree)
tree = unroot(tree)
rn = max(tree\$edge)+1
maxdm = max(dm)
ind =  which(dm==maxdm,arr=TRUE)[1,]
tmproot = Ancestors(tree, ind[1], "parent")
tree = phangorn:::reroot(tree, tmproot)
edge = tree\$edge
el = tree\$edge.length
children = tree\$edge[,2]
left = match(ind[1], children)
tmp = Ancestors(tree, ind[2], "all")
tmp= c(ind[2], tmp[-length(tmp)])
right = match(tmp, children)
if(el[left]>= (maxdm/2)){
edge = rbind(edge, c(rn, ind[1]))
edge[left,2] = rn
el[left] = el[left] - (maxdm/2)
el = c(el, maxdm/2)
}
else{
sel = cumsum(el[right])
i = which(sel>(maxdm/2))[1]
edge = rbind(edge, c(rn, tmp[i]))
edge[right[i],2] = rn
eltmp =  sel[i] - (maxdm/2)
#        el = c(el, sel[i] - (maxdm/2))
el = c(el, el[right[i]] - eltmp)
el[right[i]] = eltmp
}
tree\$edge.length = el
tree\$edge=edge
tree\$Nnode  = tree\$Nnode+1
phangorn:::reorderPruning(phangorn:::reroot(tree, rn))
}

On 9/2/10, Velzen, Robin van <Robin.vanVelzen at wur.nl> wrote:
> Dear Ape authors and mailing list members,
>
> I am new to R. and to Ape and very much impressed by the functionality the
> platform offers. I have used Ape to construct distance-based trees using the
> 'read.dna', 'dist.dna' and 'nj' functions. Now I wish to root the resulting
> Neighbor Joining tree using midpoint rooting, but have not been able to find
> the right function.
>
> Does anyone know if there is a function for midpoint rooting in Ape or
> similar R. package, or if there is a smart way to define a midpoint root
> outgroup that can be used with the 'root' function in Ape?
>
> Any help or suggestion will be much appreciated!
>
> Thanks,
>
> Robin
>
> Robin van Velzen
> PhD student
> Biosystematics Group
> Wageningen University
>
> Wageningen Campus, Radix building 107, Room W4.Aa.095
> Droevendaalsesteeg 1, 6708 PB Wageningen, The Netherlands
> PO Box 647, 6700 AP Wageningen, The Netherlands
> Tel. +31 (0)317 483425
> http://www.bis.wur.nl
>
>
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-phylo mailing list
> R-sig-phylo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-phylo
>

--
Klaus Schliep
Université Paris 6 (Pierre et Marie Curie)
9, Quai Saint-Bernard, 75005 Paris

```