R ape: find the branch length of a particular tip label
1
0
Entering edit mode
4.7 years ago

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 • 6.4k views
ADD COMMENT
1
Entering edit mode

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.

ADD REPLY
0
Entering edit mode

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)]
ADD REPLY
0
Entering edit mode

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.

ADD REPLY
1
Entering edit mode
3.8 years ago
isagvm ▴ 10

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)

ADD COMMENT
0
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 2941 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6