phytools already has a function that computes the height of all the nodes in the tree: nodHeights. If we only want to know the height of one node, then using this function is very inefficient, for obvious reasons.
The following is alternative code for computing the height of only one node. It uses the phytools internal function getAncestors, so if we are not using it as part of phytools we will first have to do:
getAncestors<-phytools:::getAncestors
And here is the function:
nodeheight<-function(tree,node){
if(node==(length(tree$tip.label)+1)) h<-0
else {
a<-setdiff(c(getAncestors(tree,node),node),
length(tree$tip.label)+1)
h<-sum(tree$edge.length[sapply(a,function(x,e)
which(e==x),e=tree$edge[,2])])
}
h
}
if(node==(length(tree$tip.label)+1)) h<-0
else {
a<-setdiff(c(getAncestors(tree,node),node),
length(tree$tip.label)+1)
h<-sum(tree$edge.length[sapply(a,function(x,e)
which(e==x),e=tree$edge[,2])])
}
h
}
That's it.
No comments:
Post a Comment
Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.