Learn R Programming

bnpsd (version 1.3.13)

tree_reorder: Reorder tree tips to best match a desired order

Description

This functions reorganizes the tree structure so that its tips appear in a desired order if possible, or in a reasonably close order when an exact solution is impossible. This tip order in the output tree is the same in both the tip labels vector (tree$tip.label) and edge matrix (tree$edge), ensured by using tree_reindex_tips() internally.

Usage

tree_reorder(tree, labels)

Arguments

tree

A phylo object from the ape package (see ape::read.tree()). Works with standard phylo objects, and also with our extended trees (in that additive edges tree$edge.length.add are recalculated after reordering if they were present).

labels

A character vector with all tip labels in the desired order. Must contain each tip label in tree exactly once.

Value

The modified tree (phylo object) with reordered edges and tips.

Details

This function has the same goal as ape::rotateConstr(), which implements a different heuristic algorithm that did not perform well in our experience.

See Also

tree_reindex_tips() to reorder tips in the labels vector to match the edge matrix order, which ensures agreement in plots (assuming plot show desired order already).

Examples

Run this code
# NOT RUN {
# create a random tree
library(ape)
k <- 5
tree <- rtree( k )
# let's set the current labels as the desired order
labels <- tree$tip.label

# now let's scramble the edges on purpose
# to create an example where reordering is needed

tree_rand <- tree
# new order of edges
indexes <- sample( Nedge( tree_rand ) )
# reorder all edge values
tree_rand$edge <- tree_rand$edge[ indexes, ]
tree_rand$edge.length <- tree_rand$edge.length[ indexes ]
# now let's reorder edges slightly so tree is more reasonable-looking
# (otherwise plot looks tangled)
tree_rand <- reorder( tree_rand, order = 'postorder' )
# the order of the tip labels in the vector and on the plot disagree with each other:
tree_rand$tip.label
plot( tree_rand )

# now reorder tree object so tips are in the desired order:
tree_rand <- tree_reorder( tree_rand, labels )
# now tip labels vector and plot should agree in order:
# (the original tree was recovered!)
tree_rand$tip.label
plot( tree_rand )

# order the tree in a different way than the original order
labels <- paste0( 't', 1 : k )
# in this case, it's often impossible to get a perfect output order
# (because the tree structure constrains the possible plot orders),
# but this function tries its best to get close to the desired order
tree2 <- tree_reorder( tree, labels )
plot(tree2)

# }

Run the code above in your browser using DataLab