This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R ape: find the branch length of a particular tip label

Hello-

I have a tree in R:

library(ape)
tree = read.tree(file)

and I would like to associate each tip label in tree$tip.label with the length of the branch immediately leading up to that tip. I know that I can pull out the branch lengths with tree$edge.length, but does anyone know how to associate these lengths with tip labels?

Thanks, Alissa

r ape phylogenetics

What do you mean by "associate these lengths with tip labels"? If it's for plotting, you should be able to do something like:

plot(tree)
edgelabels(tree$edge.length, col="blue", font=2)

Or if it's about how to retrieve which value in tree$edge.length corresponds to the which tree leave, check tree$edge. It's a two column matrix where each row is an edge whose length is in the same position in the tree$edge.length vector. The first column gives the parent node and the second gives the child node. Nodes are numbered such that the leaves are numbered first then the internal nodes so n leaves would be numbered 1:n and the internal nodes would have id>n. So tree$edge.length[tree$edge[,2] <= Ntip(tree)] should give you the lengths of all branches ending at a leave.

Thank you for your response! I have plotted the trees with tip labels and branch lengths before, so my question here is more related to your latter answer. I see that I can get the lengths of all branches ending at a leaf, but is there a way to also pull out the name on each of those leaves? As in, can I use a built-in function to retrieve the name associated with a particular branch length? If that makes sense. I want something conceptually like:

Ntipnames(tree) #not an actual function, just an example of what I want

where the tip names are in the same order as their respective branches, as outputted with

tree$edge.length[tree$edge[,2] <= Ntip(tree)]

What about tree$tip.label? In this vector the labels are in the order of the corresponding node ID, i.e. tree$tip.label[2] is the label for node with ID 2.

1 answer

Hi!

It might be this one that you need:

setNames(tree$edge.length[sapply(1:length(tree$tip.label),function(x,y) which (y==x),y=tree$edge[,2])],tree$tip.label)

awesome! I had the same problem and your answer solved it, thank you! but do you mind explaining it a bit?

Log in to answer this question.