Title: | Phylogenetic Tools for Comparative Biology (and Other Things) |
---|---|
Description: | A wide range of methods for phylogenetic analysis - concentrated in phylogenetic comparative biology, but also including numerous techniques for visualizing, analyzing, manipulating, reading or writing, and even inferring phylogenetic trees. Included among the functions in phylogenetic comparative biology are various for ancestral state reconstruction, model-fitting, and simulation of phylogenies and trait data. A broad range of plotting methods for phylogenies and comparative data include (but are not restricted to) methods for mapping trait evolution on trees, for projecting trees into phenotype space or a onto a geographic map, and for visualizing correlated speciation between trees. Lastly, numerous functions are designed for reading, writing, analyzing, inferring, simulating, and manipulating phylogenetic trees and comparative data. For instance, there are functions for computing consensus phylogenies from a set, for simulating phylogenetic trees and data under a range of models, for randomly or non-randomly attaching species or clades to a tree, as well as for a wide range of other manipulations and analyses that phylogenetic biologists might find useful in their research. |
Authors: | Liam J. Revell |
Maintainer: | Liam J. Revell <[email protected]> |
License: | GPL (>= 2) |
Version: | 2.3-19 |
Built: | 2024-11-06 16:17:29 UTC |
Source: | https://github.com/liamrevell/phytools |
phytools provides functions for phylogenetic biology: focused on phylogenetic comparative analysis, but including methods to simulate data and trees, to visualize trees and fitted models, and to analyze and manipulate phylogenetic trees and data.
The complete list of functions can be displayed with library(help=phytools)
.
The phytools development page is https://github.com/liamrevell/phytools/. More information on phytools can also be found at http://blog.phytools.org or http://www.phytools.org.
If you use phytools (or other packages that depend on phytools) in a publication, please cite it.
The appropriate citation for phytools is listed below or can be obtained using citation("phytools")
with the package installed.
Liam J. Revell
Maintainer: Liam J. Revell <[email protected]>
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Adds an arrow or a set of arrows to a plotted tree.
add.arrow(tree=NULL, tip, ...)
add.arrow(tree=NULL, tip, ...)
tree |
an object of class |
tip |
label of tip or tip or node number; or vector of such values. If |
... |
optional arguments to control the shape and size of the arrow including: its length ( |
Trees can be plotted using phytools function plotTree
, plotSimmap
, contMap
, densityMap
, and ape S3 method plot.phylo
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## show arrows with a black outline data(anoletree) plotTree(anoletree,type="fan",fsize=0.7,ftype="i") add.arrow(anoletree,tip=c("cuvieri","krugi", "pulchellus","poncensis","stratulus", "evermanni","cooki","cristatellus", "gundlachi","occultus"),lwd=5,arrl=1) add.arrow(anoletree,tip="cuvieri",col="green", lwd=3,arrl=1) add.arrow(anoletree,tip=c("krugi","pulchellus", "poncensis"),col="#E4D96F",lwd=3,arrl=1) add.arrow(anoletree,tip=c("stratulus","evermanni"), col="darkgreen",lwd=3,arrl=1) add.arrow(anoletree,tip=c("cooki","cristatellus", "gundlachi"),col="brown",lwd=3,arrl=1) add.arrow(anoletree,tip="occultus",col="darkgrey", lwd=3,arrl=1) legend(x="topleft",c("crown-giant","grass-bush","trunk-crown","trunk-ground", "twig"),pch=22,pt.bg=c("green","#E4D96F","darkgreen", "brown","darkgrey"),cex=0.9, pt.cex=2,title="PR ecomorphs",bty="n") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
## show arrows with a black outline data(anoletree) plotTree(anoletree,type="fan",fsize=0.7,ftype="i") add.arrow(anoletree,tip=c("cuvieri","krugi", "pulchellus","poncensis","stratulus", "evermanni","cooki","cristatellus", "gundlachi","occultus"),lwd=5,arrl=1) add.arrow(anoletree,tip="cuvieri",col="green", lwd=3,arrl=1) add.arrow(anoletree,tip=c("krugi","pulchellus", "poncensis"),col="#E4D96F",lwd=3,arrl=1) add.arrow(anoletree,tip=c("stratulus","evermanni"), col="darkgreen",lwd=3,arrl=1) add.arrow(anoletree,tip=c("cooki","cristatellus", "gundlachi"),col="brown",lwd=3,arrl=1) add.arrow(anoletree,tip="occultus",col="darkgrey", lwd=3,arrl=1) legend(x="topleft",c("crown-giant","grass-bush","trunk-crown","trunk-ground", "twig"),pch=22,pt.bg=c("green","#E4D96F","darkgreen", "brown","darkgrey"),cex=0.9, pt.cex=2,title="PR ecomorphs",bty="n") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
This function adds a color gradient legend to an existing plot.
add.color.bar(leg, cols, title=NULL, lims=c(0,1), digits=1, prompt=TRUE, lwd=4, outline=TRUE, ...)
add.color.bar(leg, cols, title=NULL, lims=c(0,1), digits=1, prompt=TRUE, lwd=4, outline=TRUE, ...)
leg |
numerical value for the length of the legend. |
cols |
colors for the legend. |
title |
text to plot above the bar. |
lims |
range for the bar. |
digits |
digits for plotted numbers. |
prompt |
logical value indicating whether the location of the legend should be obtained interactively. |
lwd |
width of the plotted bar. |
outline |
logical value indicated whether or not to outline the plotted color bar with a 1 pt line. |
... |
optional arguments including: |
This function was designed to add a color bar to a plot created by plotBranchbyTrait
. A color bar can be added by clicking on a location within the plot (when prompt=TRUE
) or by setting prompt=FALSE
and supplying x & y coordinates for the object.
The function is also used internally by S3 methods plot.contMap
and plot.densityMap
, as well as by errorbar.contMap
.
Liam Revell [email protected]
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
contMap
, densityMap
, errorbar.contMap
, plotBranchbyTrait
This function adds a tip to all branches of the tree and returns a a list of trees as an object of class "multiPhylo"
.
add.everywhere(tree, tip.name)
add.everywhere(tree, tip.name)
tree |
an object of class |
tip.name |
a string containing the name of the tip to add. |
A list of trees as an object of class "multiPhylo"
. Since the tip can be added to any branch, the length of the list is equal to the number of edges in tree
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function adds new tips at random to a tree with branch lengths.
add.random(tree, n=NULL, tips=NULL, edge.length=NULL, order=c("random","input"))
add.random(tree, n=NULL, tips=NULL, edge.length=NULL, order=c("random","input"))
tree |
an object of class |
n |
a number of tips to add to the tree. If |
tips |
a set of tip names for the added tips. If |
edge.length |
terminal edge length for the added tips. If |
order |
addition order for the new tips. |
If no edge lengths are provided, and the tree is ultrametric, then edge lengths are assigned to keep the tree ultrametric.
The probability that at new tip is added along any branch is directly proportional to the length of the branch.
Note that sometimes the resultant tree plotted with plot.phylo
or plotSimmap
may display with branches crossing. If so, the tree can be 'untangled' using untangle
.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Adds a legend (by default, interactively) to a plotted stochastic character mapped tree.
add.simmap.legend(leg=NULL, colors, prompt=TRUE, vertical=TRUE, ...)
add.simmap.legend(leg=NULL, colors, prompt=TRUE, vertical=TRUE, ...)
leg |
states for the discrete character in the order of |
colors |
colors for the legend in the order of |
prompt |
logical value indicating whether the location of the legend should be obtained interactively (i.e., by clicking in the plotting area). |
vertical |
logical value indicating whether to plot the legend vertically (if |
... |
optional arguments including: |
Redundant with legend
, which is much more powerful but somewhat more complicated to use.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
add.species.to.genus
adds an additional species to a genus on a phylogeny.
genus.to.species.tree
simulates pure-birth subtrees and then binds them at a random height along the terminal edge leading to each corresponding genus on a genus-level backbone tree.
add.species.to.genus(tree, species, genus=NULL, where=c("root","random")) genus.to.species.tree(tree, species)
add.species.to.genus(tree, species, genus=NULL, where=c("root","random")) genus.to.species.tree(tree, species)
tree |
an object of class |
species |
string contain species name in the format |
genus |
for |
where |
for |
For add.species.to.genus
, if genus
contains only one species and where="root"
, then species
will be attached midway along the branch leading to the one species. If where="random"
then species
will be added at a random position along the edge.
If genus
cannot be found in the tree, then the original tree is returned and a warning printed. If the tree is not ultrametric, then the resultant tree may not contain branch lengths and a warning will be printed.
Note that for some cases in which a tree is read in from file, R may initially think it is ultrametric, but then later (as tips are added) decide that it is not due to rounding of the edge lengths when it was written to file. This can most likely be resolved by using force.ultrametric
to coerce the tree to be exactly ultrametric (to the maximum numerical precision permitted by R) before adding tips to the tree.
If genus
is non-monophyletic then species
will be attached to the most inclusive group containing members of genus
and a warning will be printed.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes Akaike weights based on a set of AIC values.
aic.w(aic)
aic.w(aic)
aic |
vector of Akaike Information Criterion (AIC; Akaike, 1974) values for different fitted models. If the vector has names, these names will be inherited by the vector returned by the function. |
This function computes Akaike weights from a set of AIC values obtained from fitted models.
It returns an object of class "aic.w"
which is just a vector which allows it to be automatically printed with a numerical precision of 8 significant digits.
A vector of Akaike weights.
Liam Revell [email protected]
Akaike, H. (1974) A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19, 716-723.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function creates all possible unrooted bi- and multifurcating trees and returns a list of trees as an object of class "multiPhylo"
.
allFurcTrees(n, tip.label=NULL, to.plot=TRUE)
allFurcTrees(n, tip.label=NULL, to.plot=TRUE)
n |
an integer giving the desired number of species. |
tip.label |
an optional vector of length n containing the tip names. |
to.plot |
an optional logical value indicating whether or not to plot the trees. |
This function should be used with extreme caution for n
greater than about 8, as in this case the number of possible trees is extremely large.
A list of trees as an object of class "multiPhylo"
.
Liam Revell [email protected]
Felsenstein, J. 2004. Inferring Phylogenies. Sinauer.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## compute & plot all bi- and multifurcating ## trees for six taxa trees<-allFurcTrees(n=6) par(mfrow=c(16,15)) nulo<-sapply(trees,plot,type="unrooted", no.margin=TRUE) par(mfrow=c(1,1))
## compute & plot all bi- and multifurcating ## trees for six taxa trees<-allFurcTrees(n=6) par(mfrow=c(16,15)) nulo<-sapply(trees,plot,type="unrooted", no.margin=TRUE) par(mfrow=c(1,1))
This function uses Bayesian MCMC to sample from the posterior distribution for the states at internal nodes in the tree.
anc.Bayes(tree, x, ngen=10000, control=list(), ...) ## S3 method for class 'anc.Bayes' plot(x, ...) ## S3 method for class 'anc.Bayes' density(x, ...)
anc.Bayes(tree, x, ngen=10000, control=list(), ...) ## S3 method for class 'anc.Bayes' plot(x, ...) ## S3 method for class 'anc.Bayes' density(x, ...)
tree |
an object of class |
x |
a vector of tip values for species; |
ngen |
a integer indicating the number of generations for the MCMC. |
control |
a list of control parameters containing the following elements: |
... |
optional arguments, including to be passed to |
plot.anc.Bayes
generates a likelihood profile plot of the MCMC by default, but can also create a profile plot for any of the sampled variables by using the optional argument what
. For instance, what=40
(or, equivalently, what="40"
) will create a profile plot of the MCMC for node 40
. Additional arguments are passed to plot
.
density.anc.Bayes
computes a posterior density from the MCMC sample. Like plot.anc.Bayes
takes the optional argument what
, but unlike plot.anc.Bayes
computes the posterior density for the root node by default. The object computed by this function is of class "density"
and can be visualized using plot.density
. Burn-in (in generations) can be set using the optional argument burnin
, otherwise it will be assumed to be 20
The print
and summary
methods for this object class also return (invisibly) a vector of estimated ancestral states based on a user-supplied burn-in (or 20% of the number of generations of MCMC, if no burn-in is provided). Burn-in can be specified with the optional argument burnin
.
anc.Bayes
returns an object of class "anc.Bayes"
including at least two components:
mcmc |
a data frame with rows |
tree |
our input phylogeny. |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
ace
, anc.ML
, anc.trend
, evol.rate.mcmc
, fastAnc
## set seed set.seed(77) ## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## run MCMC (should be run at least 1e6 generations) mcmc<-anc.Bayes(mammal.tree,ln.bodyMass, ngen=50000) print(mcmc,printlen=20) ## estimates par(mfrow=c(2,1)) plot(mcmc,bty="l",main="Likelihood-profile from MCMC", font.main=3) ## likelihood-profile plot(density(mcmc,what=Ntip(mammal.tree)+1, burnin=20000),bty="l", main="Posterior density for root state of log(body mass)", font.main=3) par(mfrow=c(1,1)) ## reset par to default
## set seed set.seed(77) ## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## run MCMC (should be run at least 1e6 generations) mcmc<-anc.Bayes(mammal.tree,ln.bodyMass, ngen=50000) print(mcmc,printlen=20) ## estimates par(mfrow=c(2,1)) plot(mcmc,bty="l",main="Likelihood-profile from MCMC", font.main=3) ## likelihood-profile plot(density(mcmc,what=Ntip(mammal.tree)+1, burnin=20000),bty="l", main="Posterior density for root state of log(body mass)", font.main=3) par(mfrow=c(1,1)) ## reset par to default
This function estimates the evolutionary parameters and ancestral states for Brownian evolution using likelihood. It is also possible (for model="BM"
) to allow for missing data for some tip taxa.
anc.ML(tree, x, maxit=2000, model=c("BM","OU","EB"), ...)
anc.ML(tree, x, maxit=2000, model=c("BM","OU","EB"), ...)
tree |
an object of class |
x |
a vector of tip values for species; |
maxit |
an optional integer value indicating the maximum number of iterations for optimization. |
model |
model of continuous character evolution on the tree. It's possible that only |
... |
optional arguments. |
Because this function relies on a high dimensional numerical optimization of the likelihood function, fastAnc
should probably be preferred for most purposes. If using anc.ML
, users should be cautious to ensure convergence.
This issue has been ameliorated in phytools >= 0.2-48 by seeding the ML optimization with the result from fastAnc
.
For model="EB"
this should also not be a problem as the numerical optimization is performed for only sig2
and r
, while the ML values of the ancestral states are obtained during every iteration of the optimization algorithmically using the re-rooting method.
An object of class "anc.ML"
with at least the following four elements (if not more, depending on model
):
sig2 |
the variance of the BM process. |
ace |
a vector with the ancestral states. |
logLik |
the log-likelihood. |
convergence |
the value of |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Schluter, D., Price, T., Mooers, A. O., and Ludwig, D. (1997) Likelihood of ancestor states in adaptive radiation. Evolution 51, 1699-1711.
ace
, anc.Bayes
, fastAnc
, optim
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## estimate ancestral state under BM model fit.BM<-anc.ML(mammal.tree,ln.bodyMass) print(fit.BM)
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## estimate ancestral state under BM model fit.BM<-anc.ML(mammal.tree,ln.bodyMass) print(fit.BM)
This function estimates the evolutionary parameters and ancestral states for Brownian evolution with a directional trend.
anc.trend(tree, x, maxit=2000)
anc.trend(tree, x, maxit=2000)
tree |
an object of class |
x |
a vector of tip values for species; |
maxit |
an optional integer value indicating the maximum number of iterations for optimization. |
Note that this will generally only work and produce sensible results for a phylogeny with some non-contemporaneous tips (i.e., a tree with some fossil species).
The function uses optim
with method=
"L-BFGS-B"
internally; however, optimization is only constrained for the sig2
which must be > 0.
An object of class "anc.trend"
with the following components:
ace |
a vector with the ancestral states. |
mu |
a trend parameter per unit time. |
sig2 |
the variance of the BM process, |
logL |
the log-likelihood. |
convergence |
the value of |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## simulate tree & data using fastBM with a trend (m!=0) tree<-rtree(n=26,tip.label=LETTERS) x<-fastBM(tree,mu=4,internal=TRUE) a<-x[as.character(1:tree$Nnode+Ntip(tree))] x<-x[tree$tip.label] ## fit no trend model fit.bm<-anc.ML(tree,x,model="BM") print(fit.bm) ## fit trend model fit.trend<-anc.trend(tree,x) print(fit.trend) ## compare trend vs. no-trend models & estimates AIC(fit.bm,fit.trend) layout(matrix(c(3,4,1,2,5,6),3,2,byrow=TRUE), heights=c(1.5,3,1.5),widths=c(3,3)) xlim<-ylim<-range(c(a,fit.bm$ace, fit.trend$ace)) plot(a,fit.bm$ace,pch=19, col=make.transparent("blue",0.5), xlab="true ancestral states", ylab="ML estimates", main=paste("Comparison of true and estimated", "\nstates under a no-trend model"),font.main=3, cex.main=1.2,bty="l",cex=1.5, xlim=xlim,ylim=ylim) lines(xlim,ylim,lty="dotted") plot(a,fit.trend$ace,pch=19, col=make.transparent("blue",0.5), xlab="true ancestral states", ylab="ML estimates", main=paste("Comparison of true and estimated", "\nstates under a trend model"),font.main=3, cex.main=1.2,bty="l",cex=1.5, xlim=xlim,ylim=ylim) lines(xlim,ylim,lty="dotted") par(mfrow=c(1,1))
## simulate tree & data using fastBM with a trend (m!=0) tree<-rtree(n=26,tip.label=LETTERS) x<-fastBM(tree,mu=4,internal=TRUE) a<-x[as.character(1:tree$Nnode+Ntip(tree))] x<-x[tree$tip.label] ## fit no trend model fit.bm<-anc.ML(tree,x,model="BM") print(fit.bm) ## fit trend model fit.trend<-anc.trend(tree,x) print(fit.trend) ## compare trend vs. no-trend models & estimates AIC(fit.bm,fit.trend) layout(matrix(c(3,4,1,2,5,6),3,2,byrow=TRUE), heights=c(1.5,3,1.5),widths=c(3,3)) xlim<-ylim<-range(c(a,fit.bm$ace, fit.trend$ace)) plot(a,fit.bm$ace,pch=19, col=make.transparent("blue",0.5), xlab="true ancestral states", ylab="ML estimates", main=paste("Comparison of true and estimated", "\nstates under a no-trend model"),font.main=3, cex.main=1.2,bty="l",cex=1.5, xlim=xlim,ylim=ylim) lines(xlim,ylim,lty="dotted") plot(a,fit.trend$ace,pch=19, col=make.transparent("blue",0.5), xlab="true ancestral states", ylab="ML estimates", main=paste("Comparison of true and estimated", "\nstates under a trend model"),font.main=3, cex.main=1.2,bty="l",cex=1.5, xlim=xlim,ylim=ylim) lines(xlim,ylim,lty="dotted") par(mfrow=c(1,1))
By default, ancr
computes marginal ancestral states, also known as empirical Bayes posterior probabilities, conditioning on the fitted (or set) model of object
.
Can also perform joint ancestral state estimation, if the optional argument type
is set to type="joint"
.
hide.hidden
merges hidden states (if any).
ancr(object, ...) hide.hidden(object, ...) ## S3 method for class 'ancr' plot(x, args.plotTree=list(...), args.nodelabels=list(...), ...)
ancr(object, ...) hide.hidden(object, ...) ## S3 method for class 'ancr' plot(x, args.plotTree=list(...), args.nodelabels=list(...), ...)
object |
fitted Mk model (presently object of class |
... |
optional arguments. |
x |
in the case of |
args.plotTree |
arguments to be passed to |
args.nodelabels |
arguments to be passed to |
If the optional argument tips=TRUE
, then the matrix returned contains empirical Bayes posterior probabilities (marginal scaled likelihoods) for both tips and internal nodes. Otherwise (the default) only node marginal states are returned.
If the input object is a set of models (in the form of an anova
table), then ancr
will compute model-averaged marginal ancestral states (for type="marginal"
, unless the optional argument weighted=FALSE
, in which case only the best-supported model is used.
An object of class "ancr"
. In the case of type="marginal"
, this object consists of a matrix of marginal (empirical Bayes) probabilities and a likelihood. In the case of type="joint"
, the object contains a set of most-likely internal node states stored in a data frame.
Liam Revell [email protected]
Pagel, M. (1999) The Maximum Likelihood approach to reconstructing ancestral character states of discrete characters on phylogenies. Systematic Biology, 3, 612-622.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit ARD model ard_fmode<-fitMk(sunfish.tree,fmode,model="ARD", pi="fitzjohn") ## compute ancestral states anc_fmode<-ancr(ard_fmode) ## plot the results par(mfrow=c(2,1)) cols<-setNames(c("blue","red"),levels(fmode)) plot(anc_fmode, args.plotTree=list(lwd=2,direction="upwards", mar=c(0.1,1.1,2.1,1.1),fsize=0.8), args.nodelabels=list(piecol=cols), args.tiplabels=list(cex=0.3), legend="bottomright") mtext("a) marginal states under ARD model",adj=0) ## fit ER model er_fmode<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## compare models aov_fmode<-anova(er_fmode,ard_fmode) ## compute model-averaged ancestral states anc_fmode_model.averaged<-ancr(aov_fmode) plot(anc_fmode_model.averaged, args.plotTree=list(lwd=2,direction="upwards", mar=c(0.1,1.1,2.1,1.1),fsize=0.8), args.nodelabels=list(piecol=cols), args.tiplabels=list(cex=0.3), legend="bottomright") mtext("b) marginal states model-averaging ER & ARD models", adj=0) par(mar=c(5.1,4.1,4.1,2.1),mfrow=c(1,1))
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit ARD model ard_fmode<-fitMk(sunfish.tree,fmode,model="ARD", pi="fitzjohn") ## compute ancestral states anc_fmode<-ancr(ard_fmode) ## plot the results par(mfrow=c(2,1)) cols<-setNames(c("blue","red"),levels(fmode)) plot(anc_fmode, args.plotTree=list(lwd=2,direction="upwards", mar=c(0.1,1.1,2.1,1.1),fsize=0.8), args.nodelabels=list(piecol=cols), args.tiplabels=list(cex=0.3), legend="bottomright") mtext("a) marginal states under ARD model",adj=0) ## fit ER model er_fmode<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## compare models aov_fmode<-anova(er_fmode,ard_fmode) ## compute model-averaged ancestral states anc_fmode_model.averaged<-ancr(aov_fmode) plot(anc_fmode_model.averaged, args.plotTree=list(lwd=2,direction="upwards", mar=c(0.1,1.1,2.1,1.1),fsize=0.8), args.nodelabels=list(piecol=cols), args.tiplabels=list(cex=0.3), legend="bottomright") mtext("b) marginal states model-averaging ER & ARD models", adj=0) par(mar=c(5.1,4.1,4.1,2.1),mfrow=c(1,1))
This function uses Bayesian MCMC to estimate ancestral states and thresholds for a discrete character under the threshold model from quantitative genetics (Felsenstein 2012).
ancThresh(tree, x, ngen=100000, sequence=NULL, method="mcmc", model=c("BM","OU","lambda"), control=list(), ...)
ancThresh(tree, x, ngen=100000, sequence=NULL, method="mcmc", model=c("BM","OU","lambda"), control=list(), ...)
tree |
phylogenetic tree. |
x |
a named vector containing discrete character states; or a matrix containing the tip species, in rows, and probabilities of being in each state, in columns. |
ngen |
number of generations to run the MCMC. |
sequence |
assumed ordering of the discrete character state. If not supplied and |
method |
only method currently available is |
model |
model for the evolution of the liability. Options are |
control |
list containing the following elements: |
... |
additional arguments to be passed to |
According to the threshold model from evolutionary quantitative genetics, values for our observed discrete character are determined by an unseen continuous trait, normally referred to as liability. Every time the value for liability crosses a threshold, the observed discrete character changes in state.
Felsenstein (2012) first had the insight that this model could be used to study the evolution of discrete character traits on a reconstructed phylogenetic tree.
This function uses Bayesian MCMC to sample ancestral liabilities and thresholds for a discrete character evolution under the threshold model.
print
and plot
S3 methods are now available for the object class "ancThresh"
.
This function returns an object of class "ancThresh"
containing the posterior sample from our analysis, along with other components.
Liam Revell [email protected]
Felsenstein, J. (2012) A comparative method for both discrete and continuous characters using the threshold model. American Naturalist, 179, 145-156.
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## Not run: ## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## run MCMC mcmc<-ancThresh(sunfish.tree,fmode,ngen=1000000) ## plot results plot(mcmc,mar=c(0.1,0.1,4.1,0.1)) title(main="Posterior probabilities for node states", font.main=3) ## End(Not run)
## Not run: ## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## run MCMC mcmc<-ancThresh(sunfish.tree,fmode,ngen=1000000) ## plot results plot(mcmc,mar=c(0.1,0.1,4.1,0.1)) title(main="Posterior probabilities for node states", font.main=3) ## End(Not run)
Various phylogenetic datasets for comparative analysis.
data(anole.data) data(anoletree) data(ant.geog) data(ant.tree) data(bat.tree) data(bat_virus.data) data(betaCoV.tree) data(bonyfish.data) data(bonyfish.tree) data(butterfly.data) data(butterfly.tree) data(cordylid.data) data(cordylid.tree) data(darter.tree) data(eel.data) data(eel.tree) data(elapidae.tree) data(flatworm.data) data(flatworm.tree) data(liolaemid.tree) data(mammal.data) data(mammal.geog) data(mammal.tree) data(primate.data) data(primate.tree) data(salamanders) data(sunfish.data) data(sunfish.tree) data(tortoise.geog) data(tortoise.tree) data(tropidurid.data) data(tropidurid.tree) data(vertebrate.data) data(vertebrate.tree) data(wasp.data) data(wasp.trees) data(whale.tree)
data(anole.data) data(anoletree) data(ant.geog) data(ant.tree) data(bat.tree) data(bat_virus.data) data(betaCoV.tree) data(bonyfish.data) data(bonyfish.tree) data(butterfly.data) data(butterfly.tree) data(cordylid.data) data(cordylid.tree) data(darter.tree) data(eel.data) data(eel.tree) data(elapidae.tree) data(flatworm.data) data(flatworm.tree) data(liolaemid.tree) data(mammal.data) data(mammal.geog) data(mammal.tree) data(primate.data) data(primate.tree) data(salamanders) data(sunfish.data) data(sunfish.tree) data(tortoise.geog) data(tortoise.tree) data(tropidurid.data) data(tropidurid.tree) data(vertebrate.data) data(vertebrate.tree) data(wasp.data) data(wasp.trees) data(whale.tree)
anoletree
is an object of class "simmap"
. anole.data
is a data frame.
ant.tree
is an object of class "phylo"
. ant.geog
is a vector.
bat.tree
and betaCoV.tree
are objects of class "phylo"
. bat_virus.data
is a data frame.
bonyfish.tree
is an object of class "phylo"
. bonyfish.data
is a data frame.
butterfly.tree
is an object of class "phylo"
. butterfly.data
is a data frame.
cordylid.tree
is an object of class "phylo"
. cordylid.data
is a data frame.
darter.tree
is an object of class "phylo"
.
eel.tree
is an object of class "phylo"
. eel.data
is a data frame.
elapidae.tree
is an object of class "phylo"
.
flatworm.tree
is an object of class "phylo"
. flatworm.data
is a data frame.
liolaemid.tree
is an object of class "phylo"
. liolaemid.data
is a data frame.
mammal.tree
is an object of class "phylo"
. mammal.data
is a data frame. mammal.geog
is a numerical matrix.
primate.tree
is an object of class "phylo"
. primate.data
is a data frame.
salamanders
is an object of class "phylo"
.
sunfish.tree
is an object of class "simmap"
. sunfish.data
is a data frame.
tortoise.tree
is an object of class "phylo"
. tortoise.geog
is a data frame.
tropidurid.tree
is an object of class "simmap"
. tropidurid.data
is a data frame.
vertebrate.tree
is an object of class "phylo"
. vertebrate.data
is a data frame.
wasp.trees
is an object of class "multiPhylo"
. wasp.data
is a data frame.
whale.tree
is an object of class "phylo"
.
anoletree
is a phylogeny of Greater Antillean anole species with a mapped discrete character - ecomorph class. anole.data
is a data frame of morphological characters. Data and tree are from Mahler et al. (2010).
ant.tree
is a phylogeny containing 84 species of fungus farming attine ants. ant.geog
is a vector containing biogegraphic information for the species of the tree. Both the phylogeny and biogeographic information were originally published by Branstetter et al. (2017).
bat.tree
is a ML phylogeny of bats from the families Mormoopidae, Molossidae, and Phyllostomidae, based on GenBank accession numbers reported in Caraballo (2022) and estimated using phangorn. betaCoV.tree
is a ML phylogenetic tree of betacoronaviruses based on GenBank accession numbers reported in Caraballo (2022) and estimated using phangorn. bat_virus.data
is an association table of host and virus from Caraballo (2022).
butterfly.tree
and butterfly.data
are a phylogeny and dataset of habitat use in Mycalesina butterflies from Halali et al. (2020). The phylogeny of that study was adapted from one originally published by Brattstrom et al. (2020).
bonyfish.tree
and bonyfish.data
are a phylogeny and dataset of spawning mode and parental care in bony fishes from Benun Sutton and Wilson (2019). Their phylogenetic tree was adapted from a tree originally published by Betancur-R et al. (2017)
cordylid.tree
and cordylid.data
are a phylogeny and dataset of morphological traits for three different principal components axes from Broeckhoven et al. (2016).
darter.tree
is a phylogeny of 201 species of darter fish (Etheostomatinae) from Near et al. (2011).
eel.tree
and eel.data
are a phylogeny and dataset of feeding mode and maximum total length from 61 species of elopomorph eels from Collar et al. (2014).
elapidae.tree
is a reconstructed phylogeny containing 175 species of snakes of the family Elapidae from Lee et al. (2016).
flatworm.tree
and flatworm.data
are a phylogeny and dataset of habitat preferences for flatworms from Benitez-Alvarez et al. (2020). flatworm.tree
has been made ultrametric using penalized likelihood.
liolaemid.tree
and liolaemid.data
are a phylogenetic tree and phenotypic trait dataset of lizards from the family Liolaemidae from Esquerre et al. (2019).
mammal.tree
and mammal.data
are the phylogeny and dataset for mammal body size and home range size from Garland et al. (1992). mammal.geog
is a matrix containing geographic coordinates for various of the species in mammal.tree
pulled from citizen science observations registered on the iNaturalist web platform.
primate.tree
and primate.data
are a phylogeny and phenotypic trait dataset from Kirk and Kay (2004).
salamanders
is a phylogeny of Plethodon salamanders from Highton and Larson (1979). According to Wikipedia, the genus Plethodon contains 55 species in total.
sunfish.tree
and sunfish.data
are the phylogeny and dataset for Centrarchidae and buccal morphology (respectively) from Revell and Collar (2009).
tortoise.tree
and tortoise.geog
are a phylogeny and dataset of geographic coordinates for Galapagos tortoises. The geographic locality information was approximated from Figure 1 of Poulakakis et al. (2020), and the tree was estimated from nucleotide sequence data published with the same study.
tropidurid.tree
and tropidurid.data
are the phylogeny and bivariate quantitative trait dataset of tropidurid lizards from Revell et al. (2022).
vertebrate.tree
is a time-calibrated phylogeny of vertebrates and vertebrate.data
is a dataset of phenotypic traits. The phylogeny is from http://www.timetree.org/ (Hedges et al. 2006).
wasp.trees
and wasp.data
are the phylogeny and host-parasite associations from Lopez-Vaamonde et al. (2001).
whale.tree
is a phylogeny of cetaceans originally published in Steeman et al. (2009).
Benitez-Alvarez, L., A. Maria Leal-Zanchet, A. Oceguera-Figueroa, R. Lopes Ferreira, D. de Medeiros Bento, J. Braccini, R. Sluys, and M. Riutort (2020) Phylogeny and biogeography of the Cavernicola (Platyhelminthes: Tricladida): Relicts of an epigean group sheltering in caves? Molecular Phylogenetics and Evolution, 145, 106709.
Benun Sutton, F., and A. B. Wilson (2019) Where are all the moms? External fertilization predicts the rise of male parental care in bony fishes. Evolution, 73, 2451-2460.
Betancur-R, R., E. O. Wiley, G. Arratia, A. Acero, N. Bailly, M. Miya, G. Lecointre, and G. Orti (2017) Phylogenetic classification of bony fishes. BMC Ecology and Evolution, 17, 162.
Branstetter, M. G., A. Jesovnik, J. Sosa-Calvo, M. W. Lloyd, B. C. Faircloth, S. G. Brady, and T. R. Schultz (2017) Dry habitats were crucibles of domestication in the evolution of agriculture in ants. Proceedings of the Royal Society B, 284, 20170095.
Brattstrom, O., K. Aduse-Poku, E. van Bergen, V. French, and P. M. Brakefield (2020) A release from developmental bias accelerates morphological diversification in butterfly eyespots. Proceedings of the National Academy of Sciences, 177, 27474-27480.
Broeckhoven, C., G. Diedericks, C. Hui, B. G. Makhubo, P. le Fras N. Mouton (2016) Enemy at the gates: Rapid defensive trait diversification in an adaptive radiation of lizards. Evolution, 70, 2647-2656.
Caraballo, D. A. (2022) Cross-species transmission of bat coronaviruses in the Americas: Contrasting patterns between alphacoronavirus and betacoronavirus. Microbiology Spectrum, 10, e01411-22.
Collar, D. C., P. C. Wainwright, M. E. Alfaro, L. J. Revell, and R. S. Mehta (2014) Biting disrupts integration to spur skull evolution in eels. Nature Communications, 5, 5505.
Esquerre, D., D. Ramirez-Alvarez, C. J. Pavon-Vazquez, J. Troncoso-Palacios, C. F. Garin, J. S. Keogh, and A. D. Leache (2019) Speciation across mountains: Phylogenomics, species delimitation and taxonomy of the Liolaemus leopardinus clade (Squamata, Liolaemidae). Molecular Phylogenetics and Evolution, 139, 106524.
Garland, T., Jr., P. H. Harvey, and A. R. Ives (1992) Procedures for the analysis of comparative data using phylogenetically independent contrasts. Systematic Biology, 41, 18-32.
Kirk, E. C., and R. F. Kay (2004) The evolution of high visual acuity in the Anthropoidea. In: Ross, C. F., Kay R. F. (Eds), Anthropoid Origins. Developments in Primatology: Progress and Prospects, 539-602. Springer, Boston, MA.
Halali, S., E. van Bergen, C. J. Breuker, P. M. Brakefield, and O. Brattstrom (2020) Seasonal environments drive convergent evolution of a faster pace-of-life in tropical butterflies. Ecology Letters, 24, 102-112.
Hedges, S. B., J. Dudley, and S. Kumar (2006) TimeTree: A public knowledgebase of divergence times among organisms. Bioinformatics, 22, 2971-2972.
Highton, R., and A. Larson (1979) The genetic relationships of the salamanders of the genus Plethodon. Systematic Zoology, 28, 579-599.
Lee, M. S. Y., K. L. Saunders, B. King, and A. Palci (2016) Diversification rates and phenotypic evolution in venomous snakes (Elapidae). Royal Society Open Science, 3, 150277.
Lopez-Vaamonde, C., J. Y. Rasplus, G. D. Weiblen, and J. M. Cook (2001) Molecular phylogenies of fig wasps: Partial cocladogenesis of pollinators and parasites. Molecular Phylogenetics and Evolution, 21, 55-71.
Mahler, D. L, L. J. Revell, R. E. Glor, and J. B. Losos (2010) Ecological opportunity and the rate of morphological evolution in the diversification of Greater Antillean anoles. Evolution, 64, 2731-2745.
Near, T. J., C. M. Bossu, G. S. Bradburd, R. L. Carlson, R. C. Harrington, P. R. Hollingsworth Jr., B. P. Keck, and D. A. Etnier. (2011) Phylogeny and temporal diversification of darters (Percidae: Etheostomatinae). Systematic Biology, 60, 565-595.
Poulakakis, N., J. M. Miller, E. L. Jensen, L. B. Beheregaray, M. A. Russello, S. Glaberman, J. Boore, and A. Caccone. (2020) Colonization history of Galapagos giant tortoises: Insights from mitogenomes support the progression rule. Journal of Zoological Systematics and Evolutionary Research, 58, 1262-1275.
Revell, L. J., and D. C. Collar (2009) Phylogenetic analysis of the evolutionary correlation using likelihood. Evolution, 63, 1090-1100.
Revell, L. J., K. S. Toyama, and D. L. Mahler (2022) A simple hierarchical model for heterogeneity in the evolutionary correlation a phylogenetic tree. PeerJ, 10, e13910.
Steeman, M. E., M. B. Hebsgaard, R. E. Fordyce, S. Y. W. Ho, D. L. Rabosky, R. Nielsen, C. Rahbek, H. Glenner, M. V. Sorensen, and E. Willerslev (2009) Radiation of extant cetaceans driven by restructuring of the oceans. Systematic Biology, 58, 573-585.
Plots a phylogeny in a silly, ANSI graphics style.
ansi_phylo(tree, vertical=c("|","-"), ...)
ansi_phylo(tree, vertical=c("|","-"), ...)
tree |
object of class |
vertical |
character for vertical lines |
... |
optional arguments. |
A plotted tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(salamanders) ansi_phylo(salamanders) par(mar=c(5.1,4.1,4.1,2.1))
data(salamanders) ansi_phylo(salamanders) par(mar=c(5.1,4.1,4.1,2.1))
Applies the branch lengths of a reference tree to a target.
applyBranchLengths(tree, edge.length)
applyBranchLengths(tree, edge.length)
tree |
target tree. |
edge.length |
number of digits for rounding. Passed to |
This function applies the set of branch lengths from a reference tree to a target tree while reconciling any mappings (as in read.simmap
) with the new branch lengths.
An object of class "phylo"
or "simmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
"multiPhylo"
This function converts between object classes.
as.multiPhylo(x, ...) ## S3 method for class 'multiSimmap' as.multiPhylo(x, ...) ## S3 method for class 'phylo' as.multiPhylo(x, ...)
as.multiPhylo(x, ...) ## S3 method for class 'multiSimmap' as.multiPhylo(x, ...) ## S3 method for class 'phylo' as.multiPhylo(x, ...)
x |
object to be converted to |
... |
optional arguments. |
An object of class "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Extracts a Q-matrix from a fitted Mk model.
as.Qmatrix(x, ...) ## S3 method for class 'fitMk' as.Qmatrix(x, ...) ## S3 method for class 'Qmatrix' plot(x, ...) ## S3 method for class 'Qmatrix' print(x, ...)
as.Qmatrix(x, ...) ## S3 method for class 'fitMk' as.Qmatrix(x, ...) ## S3 method for class 'Qmatrix' plot(x, ...) ## S3 method for class 'Qmatrix' print(x, ...)
x |
fitted Mk model. (For instance, an object of class |
... |
optional arguments. |
This function extracts a Q-matrix (in the form of an object of class "Qmatrix"
) from a fitted Mk model.
An object of class "Qmatrix"
.
plot.Qmatrix
invisibly returns the coordinates of vertices of the plotted Q-matrix.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Internal function for posterior.evolrate
.
ave.rates(tree, shift, tips, sig1, sig2, ave.shift, showTree=TRUE)
ave.rates(tree, shift, tips, sig1, sig2, ave.shift, showTree=TRUE)
tree |
a tree. |
shift |
the shift point for this sample. |
tips |
tip names tipward of |
sig1 |
|
sig2 |
|
ave.shift |
average shift from all samples. |
showTree |
logical value indicating whether to plot the rate-stretched tree. |
A list of the rates.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
evol.rate.mcmc
, minSplit
, posterior.evolrate
Compute average trees or consensus trees by various criteria.
averageTree(trees, start=NULL, method="quadratic.path.difference", tol=1e-12, quiet=FALSE, ...) ls.consensus(trees, start=NULL, tol=1e-12, quiet=FALSE, ...) minTreeDist(tree, trees, method="quadratic.path.difference", ...)
averageTree(trees, start=NULL, method="quadratic.path.difference", tol=1e-12, quiet=FALSE, ...) ls.consensus(trees, start=NULL, tol=1e-12, quiet=FALSE, ...) minTreeDist(tree, trees, method="quadratic.path.difference", ...)
trees |
object of class |
tree |
object of class |
start |
starting tree for optimization. |
method |
distance criterion for minimization. Options are |
tol |
tolerance value for optimization. |
quiet |
logical value indicating whether to run "quietly" or not. |
... |
other arguments to be passed internally. |
The function averageTree
tries to find the (hypothetical) tree topology and branch lengths that has a minimum distance to all the trees in an input set, according to some user-specified tree distance measure.
The function ls.consensus
computes the least-squares consensus tree (Lapointe & Cucumel, 1997) from a set of input trees.
Finally, the function minTreeDist
finds the tree in the input set that is a minimum distance to all the other trees in the set. (This contrasts with averageTree
which can return a tree not in the input set.)
An object of class "phylo"
with edge lengths.
Liam Revell [email protected]
Lapointe, F.-J., G. Cucumel (1997) The average consensus procedure: Combination of weighted trees containing identical or overlapping sets of taxa. Systematic Biology, 46, 306-312.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
"birthdeath"
to raw birth & death ratesConverts an object of class "birthdeath"
(from birthdeath
) to a vector with the ML birth & death rates.
bd(x)
bd(x)
x |
object of class |
This is now somewhat obsolete as phytools now contains functions to fit birth-death and pure-birth diversification models from trees (fit.bd
and fit.yule
) that also take into account incomplete sampling fraction.
A vector.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Adds a new tip to the tree.
bind.tip(tree, tip.label, edge.length=NULL, where=NULL, position=0, interactive=FALSE, ...)
bind.tip(tree, tip.label, edge.length=NULL, where=NULL, position=0, interactive=FALSE, ...)
tree |
receptor tree. |
tip.label |
a string containing the species name for the new tip. |
edge.length |
edge length for the new tip (a scalar). |
where |
node number to attach new tip. If |
position |
distance rootward of the node to add the new tip. |
interactive |
logical value indicating whether or not the species should be added interactively. (Defaults to |
... |
arguments to be passed to |
If the tree is ultrametric and no branch length is specified, then edge.length
is scaled so that the tree remains ultrametric after the new tip is added.
Wrapper function for ape bind.tree
. Note that interactive=TRUE
works only for right-facing phylograms.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
set.seed(123) par(mfrow=c(3,1)) ## generate tree tree<-pbtree(b=0.1, n=10) ## plot original tree plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("a)",adj=0) ## add an extant tip ("t_extant") sister to taxon 't5' ## with divergence time of 4.5 Ma node <- which(tree$tip.label=="t5") tree <- bind.tip(tree, tip.label="t_extant", where=node, position=4.5) # plot to see the result plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("b)",adj=0) ## add an extinct tip ("t_extinct") sister to 't2' with ## divergence time of 7.8 Ma and duration (edge length) of ## 3.3 Ma node <- which(tree$tip.label=="t2") tree <- bind.tip(tree, tip.label="t_extinct", where=node, position=7.8, edge.length=3.3) ## plot to see the result plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("c)",adj=0) par(mar=c(5.1,4.1,4.1,2.1),mfrow=c(1,1))
set.seed(123) par(mfrow=c(3,1)) ## generate tree tree<-pbtree(b=0.1, n=10) ## plot original tree plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("a)",adj=0) ## add an extant tip ("t_extant") sister to taxon 't5' ## with divergence time of 4.5 Ma node <- which(tree$tip.label=="t5") tree <- bind.tip(tree, tip.label="t_extant", where=node, position=4.5) # plot to see the result plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("b)",adj=0) ## add an extinct tip ("t_extinct") sister to 't2' with ## divergence time of 7.8 Ma and duration (edge length) of ## 3.3 Ma node <- which(tree$tip.label=="t2") tree <- bind.tip(tree, tip.label="t_extinct", where=node, position=7.8, edge.length=3.3) ## plot to see the result plotTree(tree,mar=c(2.1,0.1,2.1,0.1)) axisPhylo() mtext("c)",adj=0) par(mar=c(5.1,4.1,4.1,2.1),mfrow=c(1,1))
"simmap"
This function grafts tree y
onto tree x
at node where
.
bind.tree.simmap(x, y, where="root")
bind.tree.simmap(x, y, where="root")
x |
an object of class |
y |
an object of class |
where |
node number to attach new tip, or the root node if |
This function wraps around bind.tree
for objects of class "simmap"
; however it presently only allows y
to be grafted at a node of x
and it does not allow y
to possess a root edge.
An object of class "simmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Conducts a discrete-time Brownian motion simulation on an input tree, plots the outcome, and returns the tip and internal node states to the user as a named vector.
bmPlot(tree, type="BM", anc=0, sig2=1/1000, ngen=1000, ...)
bmPlot(tree, type="BM", anc=0, sig2=1/1000, ngen=1000, ...)
tree |
a phylogenetic tree in |
type |
the type of plot to create. See Description. |
anc |
the ancestral value for the root node. |
sig2 |
the BM rate (variance of the Brownian evolution process), |
ngen |
number of generations for the simulation: will rescale the tree to this total length. |
... |
arguments to be passed to different methods. |
The function will first rescale and round the branch lengths to integer length, if they are not already in integer values. If integer branch lengths are provided, the user should also set ngen
to be equal to the total height of the tree in generations (and thus avoid rescaling).
For type="threshold"
the visualization is of the threshold model (Felsenstein 2012), in which the evolving character is liability and the segments of evolution are colored by their value for the threshold trait. If type="threshold"
is used, the function requires at least one addition input: thresholds
, a vector containing the ordered thresholds between states. The user can also provide the colors for plotting in colors
. Note that one more color than threshold should be provided as one threshold implies two states; two thresholds, three states; etc. If no value for colors
is provided, the function will recycle a set of four colors up to the number of times required by thresholds
. Finally, the optional argument return.tree=TRUE
will tell the function to return a list with the tip and note states and an object of class "phylo"
with (for type="threshold"
), the state for the threshold model through time mapped on the branches of the tree in discrete time.
This function conducts and plots discrete time Brownian simulation and returns a vector containing the simulated states at internal nodes and tips of the tree.
It also returns, by default (although this can be turned off) a tree with the branch lengths in discrete time and with a mapped discrete character (for type="threshold"
).
Liam Revell [email protected]
Felsenstein, J. (2012) A comparative method for both discrete and continuous characters using the threshold model. American Naturalist, 179, 145-156.
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
fastBM
, pbtree
, phenogram
, threshBayes
set.seed(999) ## plot BM simulation on 12 taxon tree tree<-pbtree(n=12) par(mfrow=c(1,2),mar=c(5.1,4.1,4.1,0.1)) x<-bmPlot(tree,bty="l") plotTree(tree,direction="upwards", mar=c(5.1,0.1,4.1,1.1),ftype="off") ## reset par to default values par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1)) ## plot simulation of a threshold character par(mfrow=c(1,2),mar=c(5.1,4.1,4.1,0.1)) tt<-bmPlot(tree,type="threshold",thresholds=c(0,1,2), bty="l") plot(tt$tree,direction="upwards", mar=c(5.1,0.1,4.1,1.1),ftype="off", colors=setNames(c("black","red","blue"), letters[1:3]),lwd=3) ## reset par to default values par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1))
set.seed(999) ## plot BM simulation on 12 taxon tree tree<-pbtree(n=12) par(mfrow=c(1,2),mar=c(5.1,4.1,4.1,0.1)) x<-bmPlot(tree,bty="l") plotTree(tree,direction="upwards", mar=c(5.1,0.1,4.1,1.1),ftype="off") ## reset par to default values par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1)) ## plot simulation of a threshold character par(mfrow=c(1,2),mar=c(5.1,4.1,4.1,0.1)) tt<-bmPlot(tree,type="threshold",thresholds=c(0,1,2), bty="l") plot(tt$tree,direction="upwards", mar=c(5.1,0.1,4.1,1.1),ftype="off", colors=setNames(c("black","red","blue"), letters[1:3]),lwd=3) ## reset par to default values par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1))
Fits a bounded Brownian motion model using the discrete approximation of Boucher & Demery (2016).
bounded_bm(tree, x, lims=NULL, ...)
bounded_bm(tree, x, lims=NULL, ...)
tree |
object of class |
x |
continuous character data in a vector. |
lims |
bounds. If |
... |
optional arguments. |
Optional arguments.
An object of class "bounded_bm"
.
Liam Revell [email protected]
Boucher, F. C., and V. Demery (2016) Inferring bounded evolution in phenotypic characters from phylogenetic comparative data. Systematic Biology, 65, 651-661.
Juhn, M., K. Martinet, F. Boucher, A. Schultz, L. Harmon, K. Burns, and M. Alfaro (In review) A wrapped Brownian motion model for the evolution of color.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function creates an animation of branching random diffusion (i.e., Brownian motion evolution with speciation).
branching.diffusion(sig2=1, b=0.0023, time.stop=1000, ylim=NULL, smooth=TRUE, pause=0.02, record=NULL, path=NULL, ...)
branching.diffusion(sig2=1, b=0.0023, time.stop=1000, ylim=NULL, smooth=TRUE, pause=0.02, record=NULL, path=NULL, ...)
sig2 |
variance of BM process, |
b |
birthrate for branching process. |
time.stop |
number of generations to run. |
ylim |
y limits (for plotting). |
smooth |
no longer used. |
pause |
pause (in s) between generations. |
record |
filename for video file output (no video if |
path |
full path to file for video rendering. (By default |
... |
optional arguments. |
For animation to be recorded to file, the function requires the package animation as well as a video renderer.
An animated plot and (optionally) a recorded video file.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Fits a multi-rate Brownian motion evolution model using maximum likelihood.
brownie.lite(tree, x, maxit=2000, test="chisq", nsim=100, se=NULL, ...)
brownie.lite(tree, x, maxit=2000, test="chisq", nsim=100, se=NULL, ...)
tree |
a phylogenetic tree either as an object of class |
x |
a vector of tip values for species. |
maxit |
an optional integer value indicating the maximum number of iterations for optimization - may need to be increased for large trees. |
test |
an optional string indicating the method for hypothesis testing - options are |
nsim |
number of simulations (only used if |
se |
a vector containing the standard errors for each estimated mean in |
... |
optional arguments. |
This function takes an object of class "phylo"
or class "simmap"
with a mapped binary or multi-state trait (see read.simmap
) and data for a single continuously valued character. It then fits the Brownian rate variation ("noncensored") model of O'Meara et al. (2006; Evolution). This is also the basic model implemented in Brian O'Meara's Brownie software.
Sampling error in the estimation of species means can also be accounted for by assigning the vector se
with the species specific sampling errors for x
.
An object of class "brownie.lite"
containing the following elements:
sig2.single |
is the rate, |
a.single |
is the estimated state at the root node for the single rate model. |
var.single |
variance on the single rate estimator - obtained from the Hessian. |
logL1 |
log-likelihood of the single-rate model. |
k1 |
number of parameters in the single rate model (always 2). |
sig2.multiple |
is a length p (for p rates) vector of BM rates ( |
a.multiple |
is the estimated state at the root node for the multi-rate model. |
var.multiple |
p x p variance-covariance matrix for the p rates - the square-roots of the diagonals should give the standard error for each rate. |
logL.multiple |
log-likelihood of the multi-rate model. |
k2 |
number of parameters in the multi-rate model (p+1). |
P.chisq |
P-value for a likelihood ratio test against the |
P.sim |
P-value for a likelihood ratio test against a simulated null distribution. |
convergence |
logical value indicating if the likelihood optimization converged. |
Liam Revell [email protected]
O'Meara, B. C., C. Ane, M. J. Sanderson, and P. C. Wainwright (2006) Testing for different rates of continuous trait evolution using likelihood. Evolution, 60, 922-933.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
brownieREML
, evol.vcv
, ratebytree
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest buccal.length<-setNames(sunfish.data$buccal.length, rownames(sunfish.data)) ## fit model multiBM.fit<-brownie.lite(sunfish.tree, buccal.length) print(multiBM.fit)
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest buccal.length<-setNames(sunfish.data$buccal.length, rownames(sunfish.data)) ## fit model multiBM.fit<-brownie.lite(sunfish.tree, buccal.length) print(multiBM.fit)
Fits a multi-rate Brownian motion evolution model using REML. (See brownie.lite
for more details.)
brownieREML(tree, x, maxit=2000, ...)
brownieREML(tree, x, maxit=2000, ...)
tree |
an object of class |
x |
a vector of tip values for species. |
maxit |
an optional integer value indicating the maximum number of iterations for optimization - may need to be increased for large trees. |
... |
optional arguments. |
This function takes an object of class "phylo"
or an object of class "simmap"
with a mapped binary or multi-state trait (see read.simmap
) and data for a single continuously valued character. It then uses restricted maximum likelihood (REML) to fit the Brownian rate variation ("noncensored") model of O'Meara et al. (2006; Evolution). This function is similar to brownie.lite
but uses REML (which is faster and unbiased) instead of ML. REML optimization takes advantage of Felsenstein's (1985) contrasts algorithm.
An object of class "brownieREML"
containing the following components:
sig2.single |
is the rate, |
logL1 |
log-likelihood of the single-rate model. |
sig2.multiple |
is a length p (for p rates) vector of BM rates ( |
logL2 |
log-likelihood of the multi-rate model. |
convergence |
numerical value from |
Liam Revell [email protected]
Felsenstein, J. (1985) Phylogenies and the comparative method. American Naturalist, 125, 1-15.
O'Meara, B. C., C. Ane, M. J. Sanderson, and P. C. Wainwright (2006) Testing for different rates of continuous trait evolution using likelihood. Evolution, 60, 922-933.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
brownie.lite
, evol.vcv
, evol.rate.mcmc
, ratebytree
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest gape.width<-setNames(sunfish.data$gape.width, rownames(sunfish.data)) ## fit model multiBM.reml<-brownieREML(sunfish.tree, gape.width) print(multiBM.reml)
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract character of interest gape.width<-setNames(sunfish.data$gape.width, rownames(sunfish.data)) ## fit model multiBM.reml<-brownieREML(sunfish.tree, gape.width) print(multiBM.reml)
This function adds clade labels to a plotted tree.
cladelabels(tree=NULL, text, node, offset=NULL, wing.length=NULL, cex=1, orientation="vertical") arc.cladelabels(tree=NULL, text, node=NULL, ln.offset=1.02, lab.offset=1.06, cex=1, orientation="curved", stretch=1, ...)
cladelabels(tree=NULL, text, node, offset=NULL, wing.length=NULL, cex=1, orientation="vertical") arc.cladelabels(tree=NULL, text, node=NULL, ln.offset=1.02, lab.offset=1.06, cex=1, orientation="curved", stretch=1, ...)
tree |
an object of class |
text |
desired clade label text. |
node |
node number for the most recent common ancestor of members of the clade. For |
offset |
offset (as a multiplier of character width) for the label. Defaults to |
wing.length |
length of the wings to add to the top & bottom of the label bar (in character widths). |
cex |
character expansion factor. |
orientation |
orientation of the text. Can be |
ln.offset |
line offset (as a function of total tree height) for |
lab.offset |
label offset for |
stretch |
argument for |
... |
optional arguments for |
cladelabels
presently works only for rightward facing plotted phylogenies - but no warning will be returned if your tree does not conform to this requirement!
arc.cladelabels
is designed to do a similar thing to cladelabels
, but for plotted fan trees. This function checks to ensure that the most recently plotted tree was plotted with type="fan"
style.
Liam Revell [email protected]
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Collapses a subtree to a star.
collapse.to.star(tree, node)
collapse.to.star(tree, node)
tree |
an object of class |
node |
node for the clade to be collapsed. |
If the tree has edge lengths, the function will keep the tips at the same height above the root as in the original tree.
If node
is the global root of the tree a star phylogeny will be created.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Function creates an interactive visualization of collapsing & expanding clades on the tree.
collapseTree(tree, ...)
collapseTree(tree, ...)
tree |
an object of class |
... |
optional arguments. These mostly match the arguments of |
Function first plots a fan style tree, and then the user collapses node on the tree by clicking on them. Collapsed nodes are collapsed to the common ancestor of the clade. Nodes that have been collapsed can also be expanded by clicking. Right-click (or select Finish button in RStudio) to end.
Note, for the animation to work probably when run in the RStudio IDE the "zoom" level should be set to 100%.
Returns the final plotted tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## Not run: data(liolaemid.tree) pruned<-collapseTree(liolaemid.tree,fsize=0.5) ## End(Not run)
## Not run: data(liolaemid.tree) pruned<-collapseTree(liolaemid.tree,fsize=0.5) ## End(Not run)
Creates a visual comparison of two chronograms that differ in edge lengths but not topology.
compare.chronograms(t1, t2, ...)
compare.chronograms(t1, t2, ...)
t1 |
object of class |
t2 |
object of class |
... |
optional arguments. |
This function plots two trees, with semi-transparent colors by default, & uses arrows to highlight differences in depth of corresponding nodes between the trees.
Function creates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes consensus edge lengths from a set of input trees using multiple methods.
consensus.edges(trees, method=c("mean.edge","least.squares"), ...)
consensus.edges(trees, method=c("mean.edge","least.squares"), ...)
trees |
object of class |
method |
method for computing the edge lengths. Could be the mean of all trees in which the edge is present, or it could be the least-squares edge lengths computed on the mean patristic distance matrices from the input phylogenies in |
... |
optional arguments, the most popular of which is |
An object of class "phylo"
with edge lengths.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Projects the observed and reconstructed values of a continuous trait onto the edges of a tree using a color gradient.
contMap(tree, x, res=100, fsize=NULL, ftype=NULL, lwd=4, legend=NULL, lims=NULL, outline=TRUE, sig=3, type="phylogram", direction="rightwards", plot=TRUE, ...) ## S3 method for class 'contMap' plot(x, ...) errorbar.contMap(obj, ...)
contMap(tree, x, res=100, fsize=NULL, ftype=NULL, lwd=4, legend=NULL, lims=NULL, outline=TRUE, sig=3, type="phylogram", direction="rightwards", plot=TRUE, ...) ## S3 method for class 'contMap' plot(x, ...) errorbar.contMap(obj, ...)
tree |
object of class |
x |
a numerical vector of phenotypic trait values for species. |
res |
resolution for gradient plotting. Larger numbers (to a point) indicate a finer (smoother) gradient. |
fsize |
relative font size - can be a vector of length 2 in which the first element gives the font size for the tip labels & the second element giving the font size for the legend. |
ftype |
font type - see options in |
lwd |
line width for branches. Can be a single integer number or a vector. In the latter case, the second number will be taken to be the desired legend width. |
legend |
if |
lims |
range for the color map. By default, this will be |
outline |
logical value indicating whether or not to outline the branches of the tree in black. |
sig |
the number of decimal places to show on the legend limits. |
type |
type of plot desired. Options are |
direction |
plotting direction for |
plot |
logical value indicating whether or not to plot the tree. If |
obj |
object of class |
... |
optional arguments for |
Function plots a tree with a mapped continuous character.
The mapping is accomplished by estimating states at internal nodes using ML with fastAnc
, and then interpolating the states along each edge using equation [2] of Felsenstein (1985). This makes these interpolated values equal to the maximum likelihood estimates under a Brownian evolutionary process.
The default color palette is not recommended as it is not colorblind friendly and does not render well into gray scale; however, this can be updated using the helper function setMap
.
errorbar.contMap
adds error bars to an existing plot.
Plots a tree. An object of class "contMap"
is returned invisibly.
errorbar.contMap
adds colorful error bars to a plotted tree.
Liam Revell [email protected]
Felsenstein, J. (1985) Phylogenies and the comparative method. American Naturalist, 125, 1-15.
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., K. Schliep, E. Valderrama, and J. E. Richardson (2018) Graphs in phylogenetic comparative analysis: Anscombe's quartet revisited. Methods in Ecology and Evolution, 9, 2145-2154.
anc.ML
, densityMap
, fastAnc
, plotSimmap
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## create "contMap" object mammal.contMap<-contMap(mammal.tree, ln.bodyMass,plot=FALSE,res=200) ## change color scheme mammal.contMap<-setMap(mammal.contMap, c("white","#FFFFB2","#FECC5C","#FD8D3C", "#E31A1C")) plot(mammal.contMap,fsize=c(0.7,0.8), leg.txt="log(body mass)") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## create "contMap" object mammal.contMap<-contMap(mammal.tree, ln.bodyMass,plot=FALSE,res=200) ## change color scheme mammal.contMap<-setMap(mammal.contMap, c("white","#FFFFB2","#FECC5C","#FD8D3C", "#E31A1C")) plot(mammal.contMap,fsize=c(0.7,0.8), leg.txt="log(body mass)") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Visualize co-phylogenetic trees by multiple methods.
cophylo(tr1, tr2, assoc=NULL, rotate=TRUE, ...) ## S3 method for class 'cophylo' plot(x, ...) cotangleplot(tr1, tr2, type=c("cladogram","phylogram"), use.edge.length=TRUE, tangle=c("both","tree1","tree2"), ...)
cophylo(tr1, tr2, assoc=NULL, rotate=TRUE, ...) ## S3 method for class 'cophylo' plot(x, ...) cotangleplot(tr1, tr2, type=c("cladogram","phylogram"), use.edge.length=TRUE, tangle=c("both","tree1","tree2"), ...)
tr1 |
object of class |
tr2 |
object of class |
assoc |
matrix containing the tip labels in |
rotate |
logical argument indicating whether nodes on both trees should be rotated to attempt to match in vertical position. |
x |
in the case of |
type |
for |
use.edge.length |
for |
tangle |
for |
... |
optional arguments to be passed to |
cophylo
an object of class "cophylo"
or, in the case of plot.cophylo
, plots that object. The function can (optionally) first attempt to rotate the nodes of both trees to optimize vertical matching of tips.
If no matrix of associations, assoc
, is provided, then cophylo
will look for exact matches of tip labels between trees.
cotangleplot
creates a co-phylogenetic plot in which the edges of the matched trees are crossing and is designed to be used only on phylogenies with matching tip labels.
An object of class "cophylo"
which includes the following components or a pair of plotted facing phylogenies with links between tips as specified in assoc
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Lopez-Vaamonde et al. (2001) data(wasp.trees) data(wasp.data) ## create co-phylogenetic object wasp.cophylo<-cophylo(wasp.trees[[1]],wasp.trees[[2]], assoc=wasp.data) ## plot co-phylogenies plot(wasp.cophylo,link.type="curved",link.lwd=4, link.lty="solid",link.col=make.transparent("red", 0.25)) par(mar=c(5.1,4.1,4.1,2.1))
## load data from Lopez-Vaamonde et al. (2001) data(wasp.trees) data(wasp.data) ## create co-phylogenetic object wasp.cophylo<-cophylo(wasp.trees[[1]],wasp.trees[[2]], assoc=wasp.data) ## plot co-phylogenies plot(wasp.cophylo,link.type="curved",link.lwd=4, link.lty="solid",link.col=make.transparent("red", 0.25)) par(mar=c(5.1,4.1,4.1,2.1))
Test for cospeciation based on tree distance.
cospeciation(t1, t2, distance=c("RF","SPR"), method=c("simulation","permutation"), assoc=NULL, nsim=100, ...) ## S3 method for class 'cospeciation' plot(x, ...) ## S3 method for class 'cospeciation' print(x, ...)
cospeciation(t1, t2, distance=c("RF","SPR"), method=c("simulation","permutation"), assoc=NULL, nsim=100, ...) ## S3 method for class 'cospeciation' plot(x, ...) ## S3 method for class 'cospeciation' print(x, ...)
t1 |
object of class |
t2 |
object of class |
distance |
distance method to compare trees. |
method |
method to use (simulation of pure-birth trees, or permutation of tip labels on a fixed tree) to obtain a null distribution of tree distances via |
assoc |
matrix containing the tip labels in |
nsim |
number of simulations or permutations. |
x |
for |
... |
optional arguments. |
This function conducts a test for cospeciation based on tree distance, applying a distance metric selected by the user.
Note that this method should be prone to be quite liberal as the null hypothesis is no similarity whatsoever between the two trees!
An object of class "cospeciation"
, which includes the test-statistic, the null distribution, and a p-value for the test of the null hypothesis of no topological similarity between the two trees.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Lopez-Vaamonde et al. (2001) data(wasp.trees) data(wasp.data) ## test for cospeciation wasp.cosp<-cospeciation(wasp.trees[[1]],wasp.trees[[2]], assoc=wasp.data) print(wasp.cosp) plot(wasp.cosp) title(main=paste("Simulated distribution of RF distances\n", "between unassociated trees"),font.main=3)
## load data from Lopez-Vaamonde et al. (2001) data(wasp.trees) data(wasp.data) ## test for cospeciation wasp.cosp<-cospeciation(wasp.trees[[1]],wasp.trees[[2]], assoc=wasp.data) print(wasp.cosp) plot(wasp.cosp) title(main=paste("Simulated distribution of RF distances\n", "between unassociated trees"),font.main=3)
"simmap"
or "multiSimmap"
Count the number of changes of different types on a stochastically mapped trees or set of trees (objects of class "simmap"
or "multiSimmap"
).
countSimmap(tree, states=NULL, message=TRUE)
countSimmap(tree, states=NULL, message=TRUE)
tree |
an object of class |
states |
optional argument with the states for the mapped character. If not provided, these will be computed from the tree. This is useful if averaging across many trees, some of which may lack certain states. |
message |
optional logical argument indicating whether or not to return an informative message about the function output. |
This function takes a tree or a set of trees with a mapped discrete character (that is, an object of class "simmap"
or "multiSimmap"
), and computes the total number of character changes as well as the number of character changes between all states.
A list with up to three elements: N
is an integer value giving the total number of character changes on the tree; Tr
gives the number of of transitions between row and column states (or a matrix containing both N
and the transitions between states, in rows, for an object of class "multiPhylo"
); and (optionally) message
contains an explanatory message about the function output.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Revell & Collar (2009) data(anoletree) anoletree countSimmap(anoletree)
## load data from Revell & Collar (2009) data(anoletree) anoletree countSimmap(anoletree)
Create a 'changes through time' plot from a "multiSimmap"
object.
ctt(trees, segments=20, ...) sim.ctt(tree, Q, anc=NULL, nmaps=100, ...) sim.multiCtt(tree, Q, anc=NULL, nmaps=100, nsim=100, ...)
ctt(trees, segments=20, ...) sim.ctt(tree, Q, anc=NULL, nmaps=100, ...) sim.multiCtt(tree, Q, anc=NULL, nmaps=100, nsim=100, ...)
trees |
an object of class |
segments |
number of segments to break up the history of the tree. |
tree |
for |
Q |
for |
anc |
ancestral state at the root node for simulation. |
nmaps |
number of stochastic maps per simulation. |
nsim |
for |
... |
optional arguments. |
This function generates a 'changes through time' plot in the style of a lineage-through-time (LTT) plot. It shows the mean rate or the mean number of changes per unit time from a set of stochastic character map trees.
An object of class "ctt"
or "multiCtt"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
S3 methods to summarize the results of one or more stochastic maps.
## S3 method for class 'multiSimmap' density(x, ...) ## S3 method for class 'changesMap' plot(x, ...)
## S3 method for class 'multiSimmap' density(x, ...) ## S3 method for class 'changesMap' plot(x, ...)
x |
object of class |
... |
optional arguments. For |
density.multiSimmap
method="changes"
(the default) results in a posterior distribution of the number & types of changes on the tree.
If the package coda has been installed, then the function HPD.interval
is used to compute a 95% high probability density interval for the number of changes of each type on the tree. Otherwise, the central 95% of the posterior sample is returned as an estimate of the 95% HPD interval for each change type.
The method also computes the full posterior density for each change type using a bandwidth specified by the user.
method="densityMap"
computes a standard "densityMap"
object, and thus only permits binary characters.
plot.changesMap
plots the posterior density returned by density.multiSimmap
for method=
"changes"
.
For method="changes"
density.multiSimmap
returns an object of class "changesMap"
.
For method="densityMap"
density.multiSimmap
returns an object of class "densityMap"
.
plot.changesMap
generates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Visualize posterior probability density from stochastic mapping using a color gradient on the tree.
densityMap(trees, res=100, fsize=NULL, ftype=NULL, lwd=3, check=FALSE, legend=NULL, outline=FALSE, type="phylogram", direction="rightwards", plot=TRUE, ...) ## S3 method for class 'densityMap' plot(x, ...)
densityMap(trees, res=100, fsize=NULL, ftype=NULL, lwd=3, check=FALSE, legend=NULL, outline=FALSE, type="phylogram", direction="rightwards", plot=TRUE, ...) ## S3 method for class 'densityMap' plot(x, ...)
trees |
set of phylogenetic trees in a modified |
res |
resolution for gradient plotting. Larger numbers indicate a finer (smoother) gradient. |
fsize |
relative font size - can be a vector with the second element giving the font size for the legend. |
ftype |
font type - see options in |
lwd |
line width for branches. If a vector of two elements is supplied, the second element will be taken to be the desired width of the legend bar. |
check |
check to make sure that the topology and branch lengths of all phylogenies in |
legend |
if |
outline |
logical value indicating whether or not to outline the branches of the tree in black. |
type |
type of plot desired. Options are |
plot |
logical value indicating whether or not to plot the tree. If |
direction |
plotting direction for |
x |
for |
... |
optional arguments for |
Function plots a tree with the posterior density for a mapped character from stochastic character mapping on the tree. Since the mapped value is the probability of being in state "1", only binary [0,1] characters are allowed.
Plots a tree and returns an object of class "densityMap"
invisibly.
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
Huelsenbeck, J. P., R. Neilsen, and J. P. Bollback (2003) Stochastic mapping of morphological characters. Systematic Biology, 52, 131-138.
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
make.simmap
, plotSimmap
, read.simmap
## Not run: ## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## do stochastic mapping smap.trees<-make.simmap(sunfish.tree,fmode,model="ER", nsim=100) ## compute "densityMap" object sunfish.dmap<-densityMap(smap.trees,plot=FALSE, res=50) ## res should be higher ## plot density map plot(sunfish.dmap,lwd=5,outline=TRUE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default ## End(Not run)
## Not run: ## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## do stochastic mapping smap.trees<-make.simmap(sunfish.tree,fmode,model="ER", nsim=100) ## compute "densityMap" object sunfish.dmap<-densityMap(smap.trees,plot=FALSE, res=50) ## res should be higher ## plot density map plot(sunfish.dmap,lwd=5,outline=TRUE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default ## End(Not run)
Functions plots a posterior sample of trees, including with mapped discrete characters.
make.transparent
is used internally and converts a color to transparent with a certain user-specified alpha
level.
densityTree(trees, colors="blue", alpha=NULL, method="plotTree", fix.depth=FALSE, use.edge.length=TRUE, compute.consensus=TRUE, use.gradient=FALSE, show.axis=TRUE, ...) make.transparent(color, alpha)
densityTree(trees, colors="blue", alpha=NULL, method="plotTree", fix.depth=FALSE, use.edge.length=TRUE, compute.consensus=TRUE, use.gradient=FALSE, show.axis=TRUE, ...) make.transparent(color, alpha)
trees |
an object of class |
colors |
a color or a named vector of colors in which names correspond to mapped states in an object of class |
alpha |
transparency level for plotted trees which is passed to internally used function, |
method |
plotting method to be used internally. Can be |
fix.depth |
logical value indicating whether or not to plot trees with a fixed depth or to permit plotted trees to have different depths. |
use.edge.length |
logical value indicating whether to use the edge lengths of the input tree. Defaults to |
compute.consensus |
logical value indicating whether or not to use the tip order from a consensus tree. (Defaults to |
use.gradient |
logical value indicating whether to plot all trees slightly offset using a rainbow color gradient. (Defaults to |
show.axis |
logical value indicating whether or not to include a horizontal axis in the plot. |
... |
arguments to be passed to |
color |
in |
Function creates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Summarizes the result of one or more stochastic maps.
describe.simmap(tree, ...) ## S3 method for class 'simmap' summary(object, ...) ## S3 method for class 'multiSimmap' summary(object, ...) ## S3 method for class 'describe.simmap' plot(x, ...)
describe.simmap(tree, ...) ## S3 method for class 'simmap' summary(object, ...) ## S3 method for class 'multiSimmap' summary(object, ...) ## S3 method for class 'describe.simmap' plot(x, ...)
tree |
a single tree or a set of trees as an object of class |
object |
object of class |
x |
for S3 |
... |
optional arguments which include: |
An object of class "describe.simmap"
with the following elements:
count |
a matrix containing the number and types of transitions for each tree, if |
times |
a matrix containing the times spend in each state on each tree. |
ace |
the posterior probabilities of each node being in each state, if |
legend |
a vector containing the plot legend, if |
if class(tree)="simmap"
then the function simply returns the results of countSimmap
combined with the states at each node of the tree and a matrix containing the total and relative times spent in each state on the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Collapses or resolves polytomies in special types of phylogenetic trees. (See di2multi
and multi2di
.)
## S3 method for class 'simmap' di2multi(phy, ...) ## S3 method for class 'simmap' multi2di(phy, ...) ## S3 method for class 'multiSimmap' di2multi(phy, ...) ## S3 method for class 'multiSimmap' multi2di(phy, ...) ## S3 method for class 'contMap' di2multi(phy, ...) ## S3 method for class 'contMap' multi2di(phy, ...) ## S3 method for class 'densityMap' di2multi(phy, ...) ## S3 method for class 'densityMap' multi2di(phy, ...)
## S3 method for class 'simmap' di2multi(phy, ...) ## S3 method for class 'simmap' multi2di(phy, ...) ## S3 method for class 'multiSimmap' di2multi(phy, ...) ## S3 method for class 'multiSimmap' multi2di(phy, ...) ## S3 method for class 'contMap' di2multi(phy, ...) ## S3 method for class 'contMap' multi2di(phy, ...) ## S3 method for class 'densityMap' di2multi(phy, ...) ## S3 method for class 'densityMap' multi2di(phy, ...)
phy |
object of class |
... |
optional arguments: |
The method di2multi
collapses branches of zero length (or, more specifically, branches with length shorter than tol
) to create a polytomy in a tree or set of trees.
The method multi2di
resolves polytomies by adding branches of zero length (while preserving the mappings) in a tree or set of trees.
This methods should theoretically behave similarly to di2multi
and multi2di
from the ape package.
An object of class "simmap"
, "multiSimmap"
, "contMap"
, or "densityMap"
, depending on the class of phy
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
contMap
, densityMap
, di2multi
, make.simmap
, multi2di
, read.simmap
Creates a plot in which different sized dots/circles represent different tip values for a quantitative trait.
dotTree(tree, x, legend=TRUE, method="plotTree", standardize=FALSE, ...) dot.legend(x, y, min, max, Ntip, length=5, prompt=FALSE, method="plotTree", ...)
dotTree(tree, x, legend=TRUE, method="plotTree", standardize=FALSE, ...) dot.legend(x, y, min, max, Ntip, length=5, prompt=FALSE, method="plotTree", ...)
tree |
an object of class |
x |
vector of trait values; or a matrix. If |
legend |
logical value indicating whether or not a legend should be plotted. |
method |
tree plotting method to be used internally. Will switch to |
standardize |
a logical value indicating whether or not to standardize |
y |
y coordinate of the legend. |
min |
minimum value for |
max |
maximum value for |
Ntip |
number of tips in the plotted tree for |
length |
length of legend. |
prompt |
logical value indicating whether or not to prompt for legend position. |
... |
optional arguments. In the case of |
Function creates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## log-transform trait data log.mammal<-log(mammal.data) ## plot dotTree dotTree(mammal.tree,log.mammal,fsize=0.7, standardize=TRUE,length=10) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## log-transform trait data log.mammal<-log(mammal.data) ## plot dotTree dotTree(mammal.tree,log.mammal,fsize=0.7, standardize=TRUE,length=10) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Internal function for posterior.evolrate
.
drop.clade(tree, tip)
drop.clade(tree, tip)
tree |
object of class |
tip |
set of tips in a clade. |
Function drops the clade containing the species in tip
.
Probably should not use unless you know what you're doing.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Drops all the leaves from a tree, leaving behind only the structure leading to internal nodes.
drop.leaves(tree, ...)
drop.leaves(tree, ...)
tree |
object of class |
... |
optional arguments. Presently includes only the logical value |
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
"contMap"
or "densityMap"
Drops one or multiple tips from an object of class "contMap"
or "densityMap"
.
## S3 method for class 'contMap' drop.tip(phy, tip, ...) ## S3 method for class 'densityMap' drop.tip(phy, tip, ...) ## S3 method for class 'contMap' keep.tip(phy, tip, ...) ## S3 method for class 'densityMap' keep.tip(phy, tip, ...)
## S3 method for class 'contMap' drop.tip(phy, tip, ...) ## S3 method for class 'densityMap' drop.tip(phy, tip, ...) ## S3 method for class 'contMap' keep.tip(phy, tip, ...) ## S3 method for class 'densityMap' keep.tip(phy, tip, ...)
phy |
an object of class |
tip |
name or names of species to be dropped or kept. |
... |
optional arguments to be passed to |
These functions are equivalent to drop.tip
and keep.tip
in the ape package, but for objects of class "contMap"
and "densityMap"
.
For more information about objects of class "contMap"
or "densityMap"
, please refer to the documentation pages for contMap
or densityMap
, respectively.
An object of class "contMap"
or "densityMap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
contMap
, densityMap
, drop.tip
, drop.tip.simmap
, keep.tip
"multiSimmap"
This function drops or keeps one or multiple tips from all the trees of an object of class "multiSimmap"
.
## S3 method for class 'multiSimmap' drop.tip(phy, tip, ...) ## S3 method for class 'multiSimmap' keep.tip(phy, tip, ...)
## S3 method for class 'multiSimmap' drop.tip(phy, tip, ...) ## S3 method for class 'multiSimmap' keep.tip(phy, tip, ...)
phy |
an object of class |
tip |
name or names of species to be dropped, in a vector. |
... |
optional arguments to be passed to |
Equivalent to drop.tip
and keep.tip
in ape.
This function merely wraps drop.tip.simmap
.
An object of class "multiSimmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
drop.tip
, drop.tip.multiPhylo
, drop.tip.simmap
This function drops one or multiple tips from an object of class "simmap"
.
## S3 method for class 'simmap' drop.tip(phy, tip, ...) ## S3 method for class 'simmap' keep.tip(phy, tip, ...) extract.clade.simmap(tree, node)
## S3 method for class 'simmap' drop.tip(phy, tip, ...) ## S3 method for class 'simmap' keep.tip(phy, tip, ...) extract.clade.simmap(tree, node)
phy |
an object of class |
tip |
name or names of species to be dropped (or kept). |
node |
node number for the root node of the clade to be extracted. |
... |
optional arguments. Currently the logical argument |
tree |
for |
Equivalent to drop.tip
and keep.tip
but for a tree with a mapped discrete character.
extract.clade.simmap
is functionally equivalent to extract.clade
but preserves discrete character mappings on the tree.
Following drop.tip
in ape, the returned tree is always in "cladewise"
order.
A modified object of class "phylo"
containing the elements maps
and $mapped.edge
with the time spent in each state along each edge of the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
drop.tip
, extract.clade
, make.simmap
, read.simmap
, sim.history
Conducts the 'D-test' of Huelsenbeck et al. (2003).
Dtest(t1, t2, nsim=100, ...)
Dtest(t1, t2, nsim=100, ...)
t1 |
set of stochastic map trees (i.e., object of class |
t2 |
set of stochastic map trees (i.e., object of class |
nsim |
number of simulations to use in the test. |
... |
arguments to be passed internally to |
Note that this function has been included without much testing, and so the user should be wary.
An object of class "Dtest"
.
Liam Revell [email protected]
Huelsenbeck, J. P., R. Neilsen, and J. P. Bollback (2003) Stochastic mapping of morphological characters. Systematic Biology, 52, 131-138.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Maps a discrete character onto the edges of the tree using variable edge widths.
edge.widthMap(tree, x, ...) ## S3 method for class 'edge.widthMap' plot(x, max.width=0.9, legend="trait value", ...)
edge.widthMap(tree, x, ...) ## S3 method for class 'edge.widthMap' plot(x, max.width=0.9, legend="trait value", ...)
tree |
object of class |
x |
a numerical vector of phenotypic trait values for species. |
max.width |
maximum edge width in plot units. |
legend |
label for the plot legend. |
... |
optional arguments - especially for the |
edge.widthMap
returns an object of class "edge.widthMap"
.
plot.edge.widthMap
can be used to plot this object.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## create "edge.widthMap" object mammal.ewMap<-edge.widthMap(mammal.tree,ln.bodyMass, min.width=0.05) ## plot it plot(mammal.ewMap,legend="log(body mass)") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## create "edge.widthMap" object mammal.ewMap<-edge.widthMap(mammal.tree,ln.bodyMass, min.width=0.05) ## plot it plot(mammal.ewMap,legend="log(body mass)") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Computes the relative frequencies of character state changes along edges from a sample of stochastically mapped character histories.
edgeProbs(trees)
edgeProbs(trees)
trees |
an object of class |
The function assumes that all trees in the sample differ only in their mapped histories & not at all in topology or branch lengths.
Note that edgeProbs
only asks whether the starting and ending states of the edge differ in a particular way, and thus ignores multiple-hits along a single edge.
The object that is returned is a matrix with the state changes & the relative frequency of each state change. Rows are in the order of the matrix edge
for any of the mapped trees.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Estimates the lineage density at each node in the tree based on a biogeographic model (similar to Mahler et al. 2010).
estDiversity(tree, x, method=c("asr","simulation"), model="ER", ...)
estDiversity(tree, x, method=c("asr","simulation"), model="ER", ...)
tree |
is a phylogenetic tree in |
x |
a vector containing the biogeographic area for each of the tip taxa. |
method |
method for reconstructing ancestral biogeography. |
model |
model for ancestral character estimation. In theory, any model from |
... |
optional arguments. So far, this includes only |
Two different methods are implemented in the current version.
For method="asr"
the state at the current node, and at each position along each co-extant internal edge, is computed as the marginal (empirical Bayesian) ancestral state reconstruction using the re-rooting method of Yang (2006). The lineage density is then computed as the sum of the marginal reconstructions (posterior probabilities) times the summed marginal ancestral reconstructions across co-extant edges.
For method="simulation"
, stochastic character mapping is used to generate optional argument nsim
stochastic maps of ancestral biogeography. Then the lineage density at each node is computed as the number of co-existing lineages with the same biogeography as the focal node, averaged across stochastic maps.
The importance of this distinction may depend on the degree to which reconstructions at internal nodes are independent, which relates to the distinction between marginal and joint reconstruction (e.g., see Yang 2006).
A vector containing the estimated lineage density at each node
Liam Revell [email protected]
Mahler, D. L, L. J. Revell, R. E. Glor, and J. B. Losos. (2010) Ecological opportunity and the rate of morphological evolution in the diversification of Greater Antillean anoles. Evolution, 64, 2731-2745.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Yang, Z. (2006) Computational Molecular Evolution. Oxford University Press.
Estimates the phylogenetic location of a single rate shift on the tree using Bayesian MCMC (as described in Revell et al., 2012b).
evol.rate.mcmc(tree, x, ngen=10000, control=list(), ...) ## S3 method for class 'evol.rate.mcmc' print(x, ...) ## S3 method for class 'evol.rate.mcmc' summary(object, ...) ## S3 method for class 'summary.evol.rate.mcmc' print(x, ...) ## S3 method for class 'summary.evol.rate.mcmc' plot(x, ...)
evol.rate.mcmc(tree, x, ngen=10000, control=list(), ...) ## S3 method for class 'evol.rate.mcmc' print(x, ...) ## S3 method for class 'evol.rate.mcmc' summary(object, ...) ## S3 method for class 'summary.evol.rate.mcmc' print(x, ...) ## S3 method for class 'summary.evol.rate.mcmc' plot(x, ...)
tree |
an object of class |
x |
a vector of tip values for species in which |
ngen |
an integer value indicating the number of generations for the MCMC. |
control |
a list of control parameters containing the following elements: |
object |
for the S3 |
... |
other optional arguments. |
This function takes a phylogenetic tree and data for a single continuously valued character and uses a Bayesian MCMC approach to identify the phylogenetic location of a shift in the evolutionary rate through time.
Default values of control
are given in Revell et al. (2012b).
An object of class "evol.rate.mcmc"
consisting of at least the following elements:
mcmc |
results from the MCMC run. |
tips |
list of tips in rate |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., D. L. Mahler, P. Peres-Neto, and B. D. Redelings (2012) A new method for identifying exceptional phenotypic diversification. Evolution, 66, 135-146.
anc.Bayes
, brownie.lite
, evol.vcv
, minSplit
, posterior.evolrate
Fits a multi-regime multivariate Brownian motion model following Revell & Collar (2009).
evol.vcv(tree, X, maxit=2000, vars=FALSE, ...)
evol.vcv(tree, X, maxit=2000, vars=FALSE, ...)
tree |
an object of class |
X |
an |
maxit |
an optional integer value indicating the maximum number of iterations for optimization. This quantity may need to be increased for difficult optimizations. |
vars |
an optional logical value indicating whether or not to estimate the variances of the parameter estimates from the Hessian matrix. |
... |
optional arguments. The most important optional argument at this time is |
The function takes an object of class "simmap"
with a mapped binary or multi-state trait and data for an arbitrary number of continuously valued character. It then fits the multiple evolutionary variance-covariance matrix (rate matrix) model of Revell & Collar (2009; Evolution).
evol.vcv
performs optimization by maximizing the likelihood with respect to the Cholesky matrices using optim
. Optimization is by method="Nelder-Mead"
. Using box constraints does not make sense here as they would be applied to the Cholesky matrix rather than the target parameters. Users may have to increase maxit
for large trees and/or more than two traits.
An object of class "evol.vcv"
with the following elements:
R.single |
vcv matrix for the single rate matrix model. |
vars.single |
optionally, a matrix containing the variances of the elements of |
logL1 |
log-likelihood for single matrix model. |
k1 |
number of parameters in the single matrix model. |
R.multiple |
|
vars.multiple |
optionally, an array containing the variances of the parameter estimates in |
logL.multiple |
log-likelihood of the multi-matrix model. |
k2 |
number of parameters estimated in this model. |
P.chisq |
P-value of the |
convergence |
logical value indicating whether or not the optimization has converged. |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., and D. C. Collar (2009) Phylogenetic analysis of the evolutionary correlation using likelihood. Evolution, 63, 1090-1100.
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## fit multi-correlation model sunfish.fit<-evol.vcv(sunfish.tree,sunfish.data[,2:3]) print(sunfish.fit)
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## fit multi-correlation model sunfish.fit<-evol.vcv(sunfish.tree,sunfish.data[,2:3]) print(sunfish.fit)
Fits a multi-regime model for differences in the evolutionary variance-covariance structure or correlation between two continuous traits, following Revell & Collar (2009) and Revell et al. (2022).
evolvcv.lite(tree, X, maxit=2000, tol=1e-10, ...)
evolvcv.lite(tree, X, maxit=2000, tol=1e-10, ...)
tree |
an object of class |
X |
an |
maxit |
an optional integer value indicating the maximum number of iterations for optimization - may need to be increased for large trees. |
tol |
tolerance value for |
... |
other optional arguments. The most important optional argument is probably |
This function takes an object of class "simmap"
with a mapped binary or multi-state trait and data for two and only two continuously valued character. It then fits (by default) four different evolutionary models: common rates and correlation; different rates, common correlation; different correlations, common rates; no common structure.
In addition to the four default models specified above, evolvcv.lite
now fits an additional four additional models.
The set of models to be fit can be specified using the optional argument models
in multiple ways.
First, if left unspecified, then the four models listed above will be fit.
Second, if models
is set to "all models"
than eight models will be fit.
Lastly, one or more (up to all eight) models can be fit by encoding the models to be fit into a single vector containing a subset or all of the following elements: "1"
, "2"
, "2b"
, "3"
, "3b"
, "3c"
, and "4"
. These codes correspond to the following eight models: 1. common rates, common correlation; 2. different rates, common correlation; 2b. different rates for trait 1 only, common correlation; 2c. different rates for trait 2 only, common correlation; 3. common rates, different correlations; 3b. different rates for trait 1 only, different correlations; 3c. different rates for trait 2 only, different correlation; and 4. no common structure.
A list with the results summarized for each model.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., and D. C. Collar (2009) Phylogenetic analysis of the evolutionary correlation using likelihood. Evolution, 63, 1090-1100.
Revell, L. J., K. S. Toyama, and D. L. Mahler (2022) A simple hierarchical model for heterogeneity in the evolutionary correlation on a phylogenetic tree. PeerJ, 10, e13910.
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## fit heirarchical common-structure models sunfish.fit<-evolvcv.lite(sunfish.tree, sunfish.data[,2:3],models="all models") ## print fitted models print(sunfish.fit) ## compare models anova(sunfish.fit)
## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## fit heirarchical common-structure models sunfish.fit<-evolvcv.lite(sunfish.tree, sunfish.data[,2:3],models="all models") ## print fitted models print(sunfish.fit) ## compare models anova(sunfish.fit)
This function does exhaustive and branch & bound MP searches.
exhaustiveMP(data, tree=NULL, method="branch.and.bound")
exhaustiveMP(data, tree=NULL, method="branch.and.bound")
data |
is a |
tree |
an optional input tree (used only with |
method |
an optional string indicating which method to use: |
Should probably not be used for more than about 8 species (and definitely not more than 10 species). Performs parsimony calculations using parsimony
in the phangorn package (Schliep, 2011).
A "phylo"
or "multiPhylo"
object that is the MP tree or set of MP trees. It also returns the parsimony scores in attr(trees,"pscore")
or attr(trees[[i]],"pscore")
for the ith tree.
Liam Revell [email protected]
Felsenstein, J. (2004) Inferring Phylogenies. Sinauer.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Schliep, K. P. (2011) phangorn: phylogenetic analysis in R. Bioinformatics, 27, 592-593.
mrp.supertree
, optim.parsimony
, pratchet
Modify the tip-spacing of a plotted tree.
expand.clade(tree, node, factor=5) ## S3 method for class 'expand.clade' plot(x, ...)
expand.clade(tree, node, factor=5) ## S3 method for class 'expand.clade' plot(x, ...)
tree |
tree an object of class |
node |
node index or vector of node indices. |
factor |
expansion factor for the tip-spacing of the taxa descended from node or nodes in |
x |
for |
... |
optional arguments to be passed to |
The purpose of this function is to compute a custom tip-spacing for users who want to expand or contract the tip-spacing of the descendant taxa from a given node or nodes.
The function returns an object of class "expand.clade"
which consists of the (possibly re-ordered) tree and a numerical vector with the calculated tip spacing based on the expansion factor specified by the user.
This object can be plotted using the S3 plot
method for the object class; or it can be plotted simply by calling a standard plotting function on the tree & tip spacings.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Exports trees & character data in XML format.
export.as.xml(file, trees, X)
export.as.xml(file, trees, X)
file |
filename for export. |
trees |
a phylogenetic tree or trees in |
X |
a matrix of class |
Can be used to create input file for the program SIMMAP v1.5 (Bollback 2006).
A file.
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
make.simmap
, read.nexus
, read.simmap
, write.simmap
Plots phylogenies (or phylogenetic trees and comparative data) in a variety of different styles.
fancyTree(tree, type=c("extinction","traitgram3d","droptip","densitymap", "contmap","phenogram95","scattergram"), ..., control=list()) phyloScattergram(tree, X=NULL, ...) phenogram95(tree, x=NULL, ...)
fancyTree(tree, type=c("extinction","traitgram3d","droptip","densitymap", "contmap","phenogram95","scattergram"), ..., control=list()) phyloScattergram(tree, X=NULL, ...) phenogram95(tree, x=NULL, ...)
tree |
an object of class |
type |
the type of special plot to create. See Description. |
... |
arguments to be passed to different methods. See Description. |
control |
a list of control parameters, depending on |
X |
in |
x |
in |
This function plots a phylogeny or phylogenetic tree and comparative data in a variety of different styles, depending on the value of type
. In some instances, fancyTree
is now just a wrappe for other phytools functions, such as contMap
and densityMap
.
If type="extinction"
(or any unambiguous abbreviation) the function will plot a tree in which branches preceding the MRCA of all extant taxa and branches leading only to extinct lineages are plotted with dashed red lines.
If type="traitgram3d"
the function will plot a three dimensional traitgram (that is, a projection of the tree into three dimensional morphospace where two dimensions are the phenotypic trait and the third axis is time since the root). In this case, the additional argument X
, a matrix containing the tip values of all species (with species IDs as row names) should be supplied. Optionally, the user can also supply the matrix A
, which contains the ancestral states in the tree with rows labeled by node number.
If type="droptip"
the function will create a two panel figure in which the first panel is the tree with lineages to be pruned highlighted; and the second panel is the pruned tree. In this case, the additional argument tip
, the tip name or vector of tip names to be dropped, must be supplied.
If type="densitymap"
, a posterior probability density "heat-map" is created based on a set of trees in a "multiSimmap"
object containing a binary [0,1] mapped character. (See densityMap
for additional optional arguments if type="densitymap"
.)
If type="contmap"
, reconstructed continuous trait evolution is mapped on the tree. Again, see contMap
for additional arguments if type="contmap"
.
If type="phenogram95"
a 95% traitgram (aka. "phenogram") is plotted using transparency to visualize uncertainty at ancestral nodes and along branches. Most of the options of phenogram
are available.
Finally, if type="scattergram"
a phylogenetic scatter plot matrix containing contMap
style trees on the diagonal and phylomorphospace
plots in non-diagonal panels is produced. For this type a trait matrix X
must also be supplied. The only additional arguments available for this type are ftype
, fsize
, colors
, and label
. (See phylomorphospace
for details on how these arguments should be used.) This function calls phyloScattergram
(which is also now exported to the name space) internally. In addition to creating a plot, phyloScattergram
also returns an object of class "phyloScattergram"
which can be replotted using different options if desired.
Presently only type="traitgram3d"
uses the list control
which can be supplied the same set of control parameters as phylomorphospace3d
, as well as the control parameter maxit
which will be passed to anc.ML
.
Finally, the optional argument hold
will be passed to multiple methods if supplied. It is a logical value that indicates whether or not the output to the graphical device should be held using dev.hold
before plotting (defaults to hold=TRUE
).
This function plots different types of phylogenetic trees. For type="droptip"
the function also returns the pruned tree.
Liam Revell [email protected]
Evans, M. E. K., Smith, S. A., Flynn, R. S., Donoghue, M. J. (2009) Climate, niche evolution, and diversification of the "bird-cage" evening primroses (Oenothera, sections Anogra and Kleinia). American Naturalist, 173, 225-240.
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
contMap
, densityMap
, drop.tip
, phenogram
, phylomorphospace3d
, plot.phylo
, plotSimmap
## plot tree with extinction set.seed(10) tree<-pbtree(b=1,d=0.4,t=4) fancyTree(tree,type="extinction") ## Not run: ## plot 3D traitgram ## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) fancyTree(sunfish.tree,type="traitgram3d", X=sunfish.data[,2:3], control=list(spin=FALSE)) ## End(Not run) ## plot with dropped tips tree<-pbtree(n=30) tips<-sample(tree$tip.label)[1:10] pruned<-fancyTree(tree,type="droptip",tip=tips) par(mfrow=c(1,1)) ## reset mfrow to default ## Not run: ## plot 95-percent CI phenogram data(mammal.tree) data(mammal.data) bodyMass<-setNames(mammal.data$bodyMass, rownames(mammal.data)) fancyTree(mammal.tree,type="phenogram95",x=bodyMass, fsize=0.7,ftype="i") ## End(Not run) par(mar=c(5.1,4.1,4.1,2.1)) ## reset mar to defaults
## plot tree with extinction set.seed(10) tree<-pbtree(b=1,d=0.4,t=4) fancyTree(tree,type="extinction") ## Not run: ## plot 3D traitgram ## load data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) fancyTree(sunfish.tree,type="traitgram3d", X=sunfish.data[,2:3], control=list(spin=FALSE)) ## End(Not run) ## plot with dropped tips tree<-pbtree(n=30) tips<-sample(tree$tip.label)[1:10] pruned<-fancyTree(tree,type="droptip",tip=tips) par(mfrow=c(1,1)) ## reset mfrow to default ## Not run: ## plot 95-percent CI phenogram data(mammal.tree) data(mammal.data) bodyMass<-setNames(mammal.data$bodyMass, rownames(mammal.data)) fancyTree(mammal.tree,type="phenogram95",x=bodyMass, fsize=0.7,ftype="i") ## End(Not run) par(mar=c(5.1,4.1,4.1,2.1)) ## reset mar to defaults
Estimates ancestral states for a continuous character under maximum likelihood.
fastAnc(tree, x, vars=FALSE, CI=FALSE, ...)
fastAnc(tree, x, vars=FALSE, CI=FALSE, ...)
tree |
an object of class |
x |
a vector of tip values for species; |
vars |
a logical value indicating whether or not to compute variances on the ancestral state estimates. Variances are based on Equation (6) of Rohlf (2001). |
CI |
a logical value indicating whether or not to compute 95% confidence intervals on state estimates. |
... |
optional arguments. Presently this consists of |
This function performs (reasonably) fast estimation of the ML ancestral states for a continuous trait by taking advantage of the fact that the state computed for the root node of the tree during Felsenstein's (1985) contrasts algorithm is also the MLE of the root node. Thus, the function re-roots the tree at all internal nodes and computes the contrasts state at the root each time.
The function can also (optionally) compute variances or 95% confidence intervals on the estimates.
An object of class "fastAnc"
consisting of either: a named vector containing the states at internal nodes - names are node numbers; or a list containing ancestral state estimates (ace
), variances on the estimates (var
), and/or 95% confidence intervals (CI95
).
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## estimate ancestral body sizes fit.BM<-fastAnc(mammal.tree,ln.bodyMass,CI=TRUE) print(fit.BM,printlen=10)
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## estimate ancestral body sizes fit.BM<-fastAnc(mammal.tree,ln.bodyMass,CI=TRUE) print(fit.BM,printlen=10)
Simulates one or multiple continuous traits on the tree under various evolutionary models.
fastBM(tree, a=0, mu=0, sig2=1, bounds=c(-Inf,Inf), internal=FALSE, nsim=1, ...)
fastBM(tree, a=0, mu=0, sig2=1, bounds=c(-Inf,Inf), internal=FALSE, nsim=1, ...)
tree |
is a phylogenetic tree in |
a |
a value for ancestral state at the root node. |
mu |
an optional value for the mean of random normal changes along branches of the tree - can be used to simulate a trend if |
sig2 |
instantaneous variance of the BM process, |
bounds |
a vector with the lower and upper bounds (respectively) for bounded Brownian simulation - by default simulation is unbounded. |
internal |
logical value indicating whether or not to return states for internal nodes. |
nsim |
number of simulations. |
... |
optional arguments |
This function conducts (reasonably) fast quantitative trait simulation on a phylogeny under several different models: Brownian motion (default), BM with a trend (for mu!=0
), bounds (for bounds!=c(-Inf,
Inf)
), and OU.
A vector (for nsim=1
) or matrix containing the tip states for the n
species in the tree, and (optionally) the ancestral states for internal nodes.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## simulate 10 characters on the Anolis tree ## under Brownian motion data(anoletree) X<-fastBM(anoletree,nsim=10) head(X)
## simulate 10 characters on the Anolis tree ## under Brownian motion data(anoletree) X<-fastBM(anoletree,nsim=10) head(X)
Finds the most recent common ancestor (MRCA) for a pair of tip taxa.
fastMRCA(tree, sp1, sp2) fastHeight(tree, sp1, sp2) fastDist(tree, sp1, sp2)
fastMRCA(tree, sp1, sp2) fastHeight(tree, sp1, sp2) fastDist(tree, sp1, sp2)
tree |
an object of class |
sp1 |
species one name. |
sp2 |
species two name. |
Function (fastMRCA
) returns the most recent common ancestor (node number) for a pair of taxa; or, in the case of fastHeight
, the height above the root of the MRCA of a pair of taxa; or, in the case of fastDist
, the patristic distance between a pair of taxa.
This function is mostly redundant with findMRCA
(or findMRCA(...,type="height")
in the case of fastHeight
), but for very large trees will be considerably faster.
(Also see getMRCA
in the ape package.)
The node number of the MRCA, the height above the root (for fastHeight
), or the patristic distance between two taxa (for fastDist
).
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
tree<-pbtree(n=2000) anc<-fastMRCA(tree,"t1","t15")
tree<-pbtree(n=2000) anc<-fastMRCA(tree,"t1","t15")
Finds the most recent common ancestor (MRCA) of a set of tips.
findMRCA(tree, tips=NULL, type=c("node","height"))
findMRCA(tree, tips=NULL, type=c("node","height"))
tree |
a phylogenetic tree as an object of class |
tips |
a vector containing a set of tip labels. |
type |
either |
This function returns node number of the most recent common ancestor of a set of taxa.
If tips==NULL
and type="node"
(the default) it will return the result of a normal function call to mrca
.
If tips=NULL
and type="height"
it will return a matrix equal to that produced by vcv.phylo
.
From phytools 0.5-66 forward, findMRCA
uses getMRCA
in the ape package internally, which results in a big speed-up. Even though the two functions are thus totally redundant I have left findMRCA
in the package namespace to ensure backward compatibility.
The node number of the MRCA, or a matrix of node numbers (if tips==NULL
) - for type="node"
; or the height of the MRCA, or a matrix of heights (if tips==NULL
) - for type="height"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(anoletree) anc<-findMRCA(anoletree,c("cristatellus","cooki", "gundlachi")) plotTree(anoletree,type="fan",fsize=0.7,lwd=1) nodelabels(node=anc,frame="circle",pch=21,cex=1.5, bg="blue") legend("topleft","most recent common ancestor\nof Puerto Rican TG anoles", pch=21,pt.cex=1.5,pt.bg="blue",cex=0.7,bty="n") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
data(anoletree) anc<-findMRCA(anoletree,c("cristatellus","cooki", "gundlachi")) plotTree(anoletree,type="fan",fsize=0.7,lwd=1) nodelabels(node=anc,frame="circle",pch=21,cex=1.5, bg="blue") legend("topleft","most recent common ancestor\nof Puerto Rican TG anoles", pch=21,pt.cex=1.5,pt.bg="blue",cex=0.7,bty="n") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
Fits a birth-death (fit.bd
) or pure-birth (fit.yule
) model to a reconstructed phylogenetic tree with branch lengths.
fit.bd(tree, b=NULL, d=NULL, rho=1, ...) fit.yule(tree, b=NULL, d=NULL, rho=1, ...) lik.bd(theta, t, rho=1, N=NULL) ## S3 method for class 'fit.bd' print(x, ...)
fit.bd(tree, b=NULL, d=NULL, rho=1, ...) fit.yule(tree, b=NULL, d=NULL, rho=1, ...) lik.bd(theta, t, rho=1, N=NULL) ## S3 method for class 'fit.bd' print(x, ...)
tree |
object of class |
b |
birth (speciation) rate. Presently doesn't do anything as the rate cannot be fixed. |
d |
death (extinction) rate. Presently doesn't do anything as the rate cannot be fixed. |
rho |
sampling fraction. |
theta |
vector of |
t |
branching times for calculation of the likelihood. |
N |
number of tips in the tree. |
x |
object of class |
... |
optional arguments. |
The function fit.bd
fits a birth-death model to a phylogenetic tree with edge lengths and a (potentially) incomplete sampling fraction.
The function fit.yule
fits a pure-birth model with a (potentially) incomplete sampling fraction.
The function lik.bd
computes the likelihood of a set of birth & death rates given the set of branching times computed for a tree and a sampling fraction.
fit.bd
returns an object of class "fit.bd"
which can be printed. This object is a list containing the fitted model parameters, likelihood, optimization conditions, a summary of the optimization, and a likelihood function.
fit.yule
returns an object of class "fit.yule"
. This object is a list containing the fitted model parameter, likelihood, optimization conditions, a summary of the optimization, and a likelihood function.
Liam Revell [email protected]
Nee, S., May, R. M. and Harvey, P. H. (1994) The reconstructed evolutionary process. Philosophical Transactions of the Royal Society of London B, 344, 305-311.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Stadler, T. (2012) How can we improve the accuracy of macroevolutionary rate estimates? Systematic Biology, 62, 321-329.
data(salamanders) ## compute sampling fraction based on 55 species of Plethodon sampling.f<-Ntip(salamanders)/55 ## fit birth-death model bd.fit<-fit.bd(salamanders,rho=sampling.f) print(bd.fit) ## fit Yule model yule.fit<-fit.yule(salamanders,rho=sampling.f) print(yule.fit) ## compare b-d and yule models anova(yule.fit,bd.fit) ## create a likelihood surface for b-d model ngrid<-100 b<-seq(0.01,0.06,length.out=ngrid) d<-seq(0.005,0.03,length.out=ngrid) logL<-sapply(d,function(d,b) sapply(b,function(b,d) bd.fit$lik(c(b,d)),d=d),b=b) contour(x=b,y=d,logL,nlevels=100, xlab=expression(lambda), ylab=expression(mu),bty="l") title(main="Likelihood surface for plethodontid diversification", font.main=3) points(bd.fit$b,bd.fit$d,cex=1.5,pch=4, col="blue",lwd=2) legend("bottomright","ML solution",pch=4,col="blue", bg="white",pt.cex=1.5,pt.lwd=2)
data(salamanders) ## compute sampling fraction based on 55 species of Plethodon sampling.f<-Ntip(salamanders)/55 ## fit birth-death model bd.fit<-fit.bd(salamanders,rho=sampling.f) print(bd.fit) ## fit Yule model yule.fit<-fit.yule(salamanders,rho=sampling.f) print(yule.fit) ## compare b-d and yule models anova(yule.fit,bd.fit) ## create a likelihood surface for b-d model ngrid<-100 b<-seq(0.01,0.06,length.out=ngrid) d<-seq(0.005,0.03,length.out=ngrid) logL<-sapply(d,function(d,b) sapply(b,function(b,d) bd.fit$lik(c(b,d)),d=d),b=b) contour(x=b,y=d,logL,nlevels=100, xlab=expression(lambda), ylab=expression(mu),bty="l") title(main="Likelihood surface for plethodontid diversification", font.main=3) points(bd.fit$b,bd.fit$d,cex=1.5,pch=4, col="blue",lwd=2) legend("bottomright","ML solution",pch=4,col="blue", bg="white",pt.cex=1.5,pt.lwd=2)
fitBayes
uses Bayesian MCMC to sample terminal states (species means) as well as the parameters of an evolutionary model from their joint posterior distribution, following Revell & Reynolds (2012).
fitBayes(tree, x, ngen=10000, model="BM", method="reduced", control=list())
fitBayes(tree, x, ngen=10000, model="BM", method="reduced", control=list())
tree |
an object of class |
x |
a vector of phenotypic values for individuals; |
ngen |
a integer indicating the number of generations for the MCMC. |
model |
an evolutionary model: either |
method |
a method: either |
control |
a list of control parameters containing the following elements: |
An object of class "fitBayes"
that includes a matrix (mcmc
) with a number of rows ngen/control$sample+1
containing the posterior sample and likelihoods.
Matrix columns are labeled by species (for species means and variances), or by the corresponding evolutionary parameter.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J. and R. G. Reynolds. (2012) A new Bayesian method for fitting evolutionary models to comparative data with intraspecific variation. Evolution, 66, 2697-2707.
anc.Bayes
, brownie.lite
, evol.rate.mcmc
Fits a diversity-dependent phenotypic evolution model (similar to Mahler et al. 2010).
fitDiversityModel(tree, x, d=NULL, showTree=TRUE, tol=1e-6) ## S3 method for class 'fitDiversityModel' logLik(object, ...) ## S3 method for class 'fitDiversityModel' print(x, ...)
fitDiversityModel(tree, x, d=NULL, showTree=TRUE, tol=1e-6) ## S3 method for class 'fitDiversityModel' logLik(object, ...) ## S3 method for class 'fitDiversityModel' print(x, ...)
tree |
an object of class |
x |
a vector with tip values for a continuously distributed trait. For |
d |
a vector containing the inferred historical diversity at each node in the tree - if |
showTree |
optional logical value indicating whether to plot the tree transformation implied by the model. |
tol |
some small value by which |
object |
for |
... |
optional arguments for |
An object of class "fitDiversityModel"
consisting of the following elements:
logL |
log-likelihood of the fitted model. |
sig0 |
estimated starting value for the rate at the root of the tree, |
psi |
the estimated rate of change in the rate associated with the addition of a lineage. |
vcv |
a matrix with the variances and covariance of the estimated parameters (from the Hessian). |
Liam Revell [email protected]
Mahler, D. L, L. J. Revell, R. E. Glor, and J. B. Losos (2010) Ecological opportunity and the rate of morphological evolution in the diversification of Greater Antillean anoles. Evolution, 64, 2731-2745.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
brownie.lite
, estDiversity
, evol.rate.mcmc
The functions fitMk
, fitmultiMk
, fitpolyMk
, fitHRM
, fitMk.parallel
, fitgammaMk
, fitfnMk
, and mcmcMk
fit various flavors of the extended Mk model (Lewis, 2001) for discrete character evolution on a reconstructed phylogeny.
fitMk(tree, x, model="SYM", fixedQ=NULL, ...) ## S3 method for class 'fitMk' plot(x, ...) ## S3 method for class 'gfit' plot(x, ...) fitmultiMk(tree, x, model="ER", ...) fitpolyMk(tree, x, model="SYM", ordered=FALSE, ...) graph.polyMk(k=2, model="SYM", ordered=FALSE, ...) ## S3 method for class 'fitpolyMk' plot(x, ...) mcmcMk(tree, x, model="ER", ngen=10000, ...) ## S3 method for class 'mcmcMk' plot(x, ...) ## S3 method for class 'mcmcMk' density(x, ...) ## S3 method for class 'density.mcmcMk' plot(x, ...) fitHRM(tree, x, model="ARD", ncat=2, ...) ## S3 method for class 'fitHRM' plot(x, ...) fitMk.parallel(tree, x, model="SYM", ncores=1, ...) fitgammaMk(tree, x, model="ER", fixedQ=NULL, nrates=8, ...) fitfnMk(tree, x, model="polynomial", degree=2, ...)
fitMk(tree, x, model="SYM", fixedQ=NULL, ...) ## S3 method for class 'fitMk' plot(x, ...) ## S3 method for class 'gfit' plot(x, ...) fitmultiMk(tree, x, model="ER", ...) fitpolyMk(tree, x, model="SYM", ordered=FALSE, ...) graph.polyMk(k=2, model="SYM", ordered=FALSE, ...) ## S3 method for class 'fitpolyMk' plot(x, ...) mcmcMk(tree, x, model="ER", ngen=10000, ...) ## S3 method for class 'mcmcMk' plot(x, ...) ## S3 method for class 'mcmcMk' density(x, ...) ## S3 method for class 'density.mcmcMk' plot(x, ...) fitHRM(tree, x, model="ARD", ncat=2, ...) ## S3 method for class 'fitHRM' plot(x, ...) fitMk.parallel(tree, x, model="SYM", ncores=1, ...) fitgammaMk(tree, x, model="ER", fixedQ=NULL, nrates=8, ...) fitfnMk(tree, x, model="polynomial", degree=2, ...)
tree |
an object of class |
x |
a vector (or numeric matrix) of tip values for species; |
model |
model. See |
fixedQ |
fixed value of transition matrix |
ordered |
for |
k |
For |
ngen |
number of generations of MCMC for |
ncat |
number of rate categories (per level of the discrete trait) in the hidden-rate model. |
ncores |
number of cores for |
nrates |
number of rate categories for discretized |
degree |
the degree of the polynomial for |
... |
optional arguments, including |
The function fitMk
fits a so-called extended Mk model for discrete character evolution (Lewis, 2001).
plot.fitMk
plots an object of class "fitMk"
returned by fitMk
. plot.gfit
plots an object of class "gfit"
from geiger's fitDiscrete
function. Both plots portray the fitted model using a graph of arrows connecting states.
The function fitmultiMk
fits an Mk model in which the transition rates between character states are allowed to vary depending on the mapped state of a discrete character on the tree. It can be combined with, for example, paintSubTree
to test hypotheses about how the process of discrete character evolution for x
varies between different parts of the tree.
The function fitgammaMk
fits an Mk model in which the edge rates are assumed to have been sampled randomly from a distribution with mean of 1.0 and shape parameter
.
The function fitfnMk
fit an ordered Mk model in which the backward and forward transition rates between adjacent levels of the trait vary according to a functional form. Presently that function form is an nth degree polynomial, in which degree
is set by the user (but defaults to degree = 2
).
The function fitpolyMk
fits an Mk model to data for a discrete character with intraspecific polymorphism. Polymorphic species should be coded with the name of the two or more states recorded for the species separated by a plus sign +
(e.g., A+B
would indicate that both states A
and B
are found in the corresponding taxon). Invariably it's assumed that transitions between states must occur through a polymorphic condition, whereas transitions cannot occur directly between two incompatible polymorphic conditions. For instance, a transition between A+B
and B+C
would have to occur through the monomorphic state B
. At time of writing, this function permits the models "ER"
(equal rates for all permitted transitions), "SYM"
(symmetric backward & forward rates for all permitted transitions), "ARD"
(all-rates-different for permitted transitions), and a new model called "transient"
in which the acquisition of polymorphism (e.g., A -> A+B
) is assumed to occur at a different rate than its loss (e.g., A+B -> B
). The method plot.fitpolyMk
plots the fitted Mk model with intraspecific polymorphism.
The function mcmcMk
runs a Bayesian MCMC version of fitMk
. The shape of the prior distribution of the transition rates is , with
and
via the argument
prior
, which takes the form of a list. The default value of is 0.1, and
defaults to a value such that
is equal to the parsimony score for
x
divided by the sum of the edge lengths of the tree. The shape of the proposal distribution is normal, with mean zero and a variance that can be controlled by the user via the optional argument prior.var
. The argument auto.tune
, if TRUE
or FALSE
, indicates whether or not to 'tune' the proposal variance up or down to target a particular acceptance rate (defaults to 0.5). auto.tune
can also be a numeric value between 0 and 1, in which case this value will be the target acceptance ratio. The argument plot
indicates whether the progress of the MCMC should be plotted (defaults to TRUE
, but runs much faster when set to FALSE
).
The method plot.mcmcMk
plots a log-likelihood trace and a trace of the rate parameters from the MCMC. (This the same graph that is created by setting plot=TRUE
in mcmcMk
.) The method density.mcmcMk
computes a posterior density on the transition rates in the model from the posterior sample obtained in the MCMC, will import the package coda if it is available, and returns an object of class "density.mcmcMk"
. Finally, the method plot.density.mcmcMk
creates a plot of the posterior density (or a set of plots) for the transition rates between states.
Finally, the function fitHRM
fits a hidden-rate Mk model following Beaulieu et al. (2013). For the hidden-rate model we need to specify a number of rate categories for each level of the trait - and this can be a vector of different values for each trait. We can also choose a model ("ER"
, "SYM"
, or "ARD"
), as well as whether or not to treat the character as a 'threshold' trait (umbral=TRUE
, defaults to FALSE
). This latter model is basically one that allows absorbing conditions for some hidden states. Since this can be a difficult optimization problem, the optional argument niter
sets the number of optimization iterations to be run. niter
defaults to niter=10
. To fit the same default hidden-rates model as is implemented in corHMM, one should set corHMM_model=TRUE
and ordered_hrm=FALSE
.
Note that (by default) both fitMk
and fitmultiMk
recycle code from ace
in the ape package for computing the likelihood. (If the optional argument pruning=TRUE
then alternative, slightly faster, phytools code for the pruning algorithm is used.) fitpolyMk
, mcmcMk
, and fitHRM
use fitMk
internally to compute the likelihood.
An object of class "fitMk"
, "fitmultiMk"
, "fitpolyMk"
, "mcmcMk"
, "fitHRM"
, "fitgammaMk"
, or "fitfnMk"
. In the case of density.mcmcMk
an object of class "density.mcmcMk"
.
plot.fitMk
, plot.gfit
, and plot.HRM
invisibly return the coordinates of vertices of the plotted Q-matrix.
Liam Revell [email protected]
Beaulieu, J. M., B. C. O'Meara, and M. J. Donoghue (2013) Identifying hidden rate changes in the evolution of a binary morphological character: The evolution of plant habit in campanulid angiosperms. Systematic Biology, 62, 725-737.
FitzJohn, R. G., W. P. Maddison, and S. P. Otto (2009) Estimating trait-dependent speciation and extinction rates from incompletely resolved phylogenies. Systematic Biology, 58, 595-611.
Lewis, P. O. (2001) A likelihood approach to estimating phylogeny from discrete morphological character data. Systematic Biology, 50, 913-925.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J. and L. J. Harmon (2022) Phylogenetic Comparative Methods in R. Princeton University Press.
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit "ER" model fit.ER<-fitMk(sunfish.tree,fmode,model="ER") print(fit.ER) ## fit "ARD" model fit.ARD<-fitMk(sunfish.tree,fmode,model="ARD") print(fit.ARD) ## compare the models AIC(fit.ER,fit.ARD) ## load tree and data from Benitez-Alvarez et al. (2000) data(flatworm.data) data(flatworm.tree) ## extract discrete character (habitat) habitat<-setNames(flatworm.data$Habitat, rownames(flatworm.data)) ## fit polymorphic models "ER" and "transient" fitpoly.ER<-fitpolyMk(flatworm.tree,habitat, model="ER") fitpoly.transient<-fitpolyMk(flatworm.tree,habitat, model="transient") ## print fitted models print(fitpoly.ER) print(fitpoly.transient) ## compare model AIC(fitpoly.ER,fitpoly.transient) ## plot models par(mfrow=c(2,1)) plot(fitpoly.ER) mtext("a) ER polymorphic model",adj=0,line=1) plot(fitpoly.transient) mtext("b) Transient polymorphic model",adj=0, line=1) par(mfrow=c(1,1))
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit "ER" model fit.ER<-fitMk(sunfish.tree,fmode,model="ER") print(fit.ER) ## fit "ARD" model fit.ARD<-fitMk(sunfish.tree,fmode,model="ARD") print(fit.ARD) ## compare the models AIC(fit.ER,fit.ARD) ## load tree and data from Benitez-Alvarez et al. (2000) data(flatworm.data) data(flatworm.tree) ## extract discrete character (habitat) habitat<-setNames(flatworm.data$Habitat, rownames(flatworm.data)) ## fit polymorphic models "ER" and "transient" fitpoly.ER<-fitpolyMk(flatworm.tree,habitat, model="ER") fitpoly.transient<-fitpolyMk(flatworm.tree,habitat, model="transient") ## print fitted models print(fitpoly.ER) print(fitpoly.transient) ## compare model AIC(fitpoly.ER,fitpoly.transient) ## plot models par(mfrow=c(2,1)) plot(fitpoly.ER) mtext("a) ER polymorphic model",adj=0,line=1) plot(fitpoly.transient) mtext("b) Transient polymorphic model",adj=0, line=1) par(mfrow=c(1,1))
Fits a multi-rate discrete-state-dependent Brownian motion model using the discrete approximation of Boucher & Demery (2016).
fitmultiBM(tree, x, y=NULL, model="ER", ncat=1, ...)
fitmultiBM(tree, x, y=NULL, model="ER", ncat=1, ...)
tree |
object of class |
x |
continuous character data in a vector. |
y |
optional discrete character, normally in the form of a factor or character vector. |
model |
discrete character evolution model. (E.g., |
ncat |
number of rate categories (if hidden rates). |
... |
optional arguments. |
Optional arguments.
An object of class "fitmultiBM"
.
Liam Revell [email protected]
Boucher, F. C., and V. Demery (2016) Inferring bounded evolution in phenotypic characters from phylogenetic comparative data. Systematic Biology, 65, 651-661.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
bounded_bm
, brownie.lite
, fitMk
Fits Pagel's (1994) model for the correlated evolution of two binary characters.
fitPagel(tree, x, y, method="fitMk", model="ARD", dep.var="xy", ...) ## S3 method for class 'fitPagel' plot(x, ...)
fitPagel(tree, x, y, method="fitMk", model="ARD", dep.var="xy", ...) ## S3 method for class 'fitPagel' plot(x, ...)
tree |
an object of class |
x |
a vector of phenotypic values for a binary trait for the species in |
y |
a second binary character for the species in |
method |
function to use for optimization (defaults to |
model |
model of evolution for the individual characters. Can be |
dep.var |
dependent variable. If |
... |
optional arguments to be passed to |
fitPagel
fits both an independent evolution model, as well as Pagel's (1994) binary dependent model, and compares them with a likelihood-ratio test.
plot.fitPagel
plots the fitted models using arrows.
An object of class "fitPagel"
which contains the optimized matrices under an independence & a dependence model, log-likelihoods, a likelihood ratio, and a P-value for the independence model based on a chi-squared test.
plot.fitPagel
creates a plot showing the different fitted models with arrows.
Liam Revell [email protected]
Pagel, M. (1994) Detecting correlated evolution on phylogenies: A general method for the comparative analysis of discrete characters. Proceedings of the Royal Society B, 255, 37-45.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## Not run: ## load data data(bonyfish.tree) data(bonyfish.data) ## extract discrete characters spawning_mode<-setNames(bonyfish.data$spawning_mode, rownames(bonyfish.data)) paternal_care<-setNames(bonyfish.data$paternal_care, rownames(bonyfish.data)) ## fit correlational model bonyfish.pagel<-fitPagel(bonyfish.tree,paternal_care, spawning_mode) ## test for a difference between models anova(bonyfish.pagel) ## plot fitted models plot(bonyfish.pagel,lwd.by.rate=TRUE) ## reset par par(mar=c(5.1,4.1,4.1,2.1), mfrow=c(1,1)) ## End(Not run)
## Not run: ## load data data(bonyfish.tree) data(bonyfish.data) ## extract discrete characters spawning_mode<-setNames(bonyfish.data$spawning_mode, rownames(bonyfish.data)) paternal_care<-setNames(bonyfish.data$paternal_care, rownames(bonyfish.data)) ## fit correlational model bonyfish.pagel<-fitPagel(bonyfish.tree,paternal_care, spawning_mode) ## test for a difference between models anova(bonyfish.pagel) ## plot fitted models plot(bonyfish.pagel,lwd.by.rate=TRUE) ## reset par par(mar=c(5.1,4.1,4.1,2.1), mfrow=c(1,1)) ## End(Not run)
This function uses the discrete approximation of Boucher and Demery (2016) to fit a multi-state discrete character threshold model following Felsenstein (2012; Revell 2014).
fitThresh(tree, x, sequence=NULL, ...)
fitThresh(tree, x, sequence=NULL, ...)
tree |
object of class |
x |
a named vector. |
sequence |
assumed ordering of the discrete character state. If not supplied and then alphanumeric order is assumed. |
... |
optional arguments. |
An object of class "fitThresh"
.
Liam Revell [email protected]
Boucher, F. C., and V. Demery (2016) Inferring bounded evolution in phenotypic characters from phylogenetic comparative data. Systematic Biology, 65, 651-661.
Felsenstein, J. (2012) A comparative method for both discrete and continuous characters using the threshold model. American Naturalist, 179, 145-156.
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
ancThresh
, bounded_bm
, fitmultiBM
, threshBayes
Coerces an object of class "phylo"
to be ultrametric.
force.ultrametric(tree, method=c("nnls","extend"), ...)
force.ultrametric(tree, method=c("nnls","extend"), ...)
tree |
an object of class |
method |
the method to use to force the tree to be ultrametric. Options are |
... |
optional arguments: principally, |
force.ultrametric
coerces a non-ultrametric tree to be ultrametric.
This is achieved either by using nnls.tree
from the phangorn package to compute the set of edge lengths that result in a minimized sum-of-squares distance between the patristic distance of the output and input trees (method="nnls"
); or by simply extending all the external edges of the tree to match the external edge with the greatest total height (method="extend"
).
Note that neither of these should be treated as formal statistical methods for inferring an ultrametric tree. Rather, this method can be deployed when a genuinely ultrametric tree read from file fails is.ultrametric
for reasons of numerical precision.
An ultrametric tree in an object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Internally used function to compute the likelihood under a model.
gamma_pruning(par, nrates=4, tree, x, model=NULL, median=TRUE, expm.method="Higham08.b", ...)
gamma_pruning(par, nrates=4, tree, x, model=NULL, median=TRUE, expm.method="Higham08.b", ...)
par |
function parameters. |
nrates |
number of discrete rate categories. |
tree |
object of class |
x |
data in the form of a binary matrix. |
model |
design matrix of fitted model. |
median |
use the median of each rate category. |
expm.method |
method used for matrix exponentiation. |
... |
optional arguments. |
A value of the log-likelihood.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Conducts -test of Pybus & Harvey (2000).
gammatest(x)
gammatest(x)
x |
an object of class |
A an object of class "gammatest"
consisting of a list that contains:
gamma |
a value for the |
p |
two-tailed P-value for the |
Liam Revell [email protected]
Pybus, O. G., and P. H. Harvey (2000) Testing macro-evolutionary models using incomplete molecular phylogenies. Proc. R. Soc. Lond. B, 267, 2267-2272.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(darter.tree) gammatest(ltt(darter.tree,plot=FALSE))
data(darter.tree) gammatest(ltt(darter.tree,plot=FALSE))
Simulates DNA sequence on tree
under the specified model.
genSeq(tree, l=1000, Q=NULL, rate=1, format="DNAbin", ...)
genSeq(tree, l=1000, Q=NULL, rate=1, format="DNAbin", ...)
tree |
object of class |
l |
length of desired sequences. |
Q |
transition matrix for the simulation. Row and column names ( |
rate |
multiplier for |
format |
format of the output object. Can be |
... |
optional arguments. |
Uses sim.Mk
internally.
An object of class "DNAbin"
or "phyDat"
, or a matrix of nucleotides.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(mammal.tree) mammal.tree$edge.length<-mammal.tree$edge.length/ max(nodeHeights(mammal.tree))*0.2 ## rescale tree ## simulate gamma rate heterogeneity gg<-rgamma(n=100,shape=0.25,rate=0.25) dna<-genSeq(mammal.tree,l=100,rate=gg)
data(mammal.tree) mammal.tree$edge.length<-mammal.tree$edge.length/ max(nodeHeights(mammal.tree))*0.2 ## rescale tree ## simulate gamma rate heterogeneity gg<-rgamma(n=100,shape=0.25,rate=0.25) dna<-genSeq(mammal.tree,l=100,rate=gg)
Adds a geological legend to a plotted tree.
geo.legend(leg=NULL, colors=NULL, alpha=0.2, ...) geo.palette()
geo.legend(leg=NULL, colors=NULL, alpha=0.2, ...) geo.palette()
leg |
a matrix with the starting & ending point of each plotted era in rows, & names of the time periods as rownames. |
colors |
a vector of colors for the time periods of the rows in |
alpha |
transparency level to apply to |
... |
optional arguments. |
The function geo.legend
adds a geological (or other temporal) legend to a plotted tree.
The function geo.palette
returns a geological time color palette to the user.
geo.legend
adds a visual element to a plotted tree and invisible returns an object of class geo.legend
containing the time periods and colors of the painted legend.
geo.palette
simply returns a geological timescale color palette as an object of class "geo.palette"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(anoletree) ## rescale tree to 50 ma total depth anoletree<-rescale(anoletree,model="depth",depth=50) ## plot phylogeny plotTree(anoletree,ylim=c(-0.16,1)*Ntip(anoletree), ftype="i",lwd=1,fsize=0.5) ## add geological color legend obj<-geo.legend() par(mar=c(5.1,4.1,4.1,2.1))
data(anoletree) ## rescale tree to 50 ma total depth anoletree<-rescale(anoletree,model="depth",depth=50) ## plot phylogeny plotTree(anoletree,ylim=c(-0.16,1)*Ntip(anoletree), ftype="i",lwd=1,fsize=0.5) ## add geological color legend obj<-geo.legend() par(mar=c(5.1,4.1,4.1,2.1))
Return the phylogenetic position of a mouse click on a plotted tree.
get.treepos(message=TRUE, ...) getnode(...)
get.treepos(message=TRUE, ...) getnode(...)
message |
for |
... |
optional arguments. |
Both get.treepos
and getnode
are primarily meant for internal use in other phytools functions.
get.treepos
returns the index of the node at the end of the selected edge, along with the branch distance to that node.
getnode
simply returns the closest node to the user mouse click.
A list for get.treepos
and a node number for getnode
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function gets all subtrees that cannot be further subdivided into two reciprocally monophyletic subtrees of size >= clade.size
.
getCladesofSize(tree, clade.size=2)
getCladesofSize(tree, clade.size=2)
tree |
is an object of class |
clade.size |
subtree size. |
An object of class "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Returns the descendants or parent of a specified node.
getDescendants(tree, node, curr=NULL) getParent(tree, node)
getDescendants(tree, node, curr=NULL) getParent(tree, node)
tree |
a phylogenetic tree as an object of class |
node |
an integer specifying a node number in the tree. |
curr |
the set of previously stored node numbers - used in recursive function calls. |
getDescendants
returns the set of node & tip numbers descended from node
.
getParent
returns the single parent node of a specified node number (or NULL
if node
is already the root).
The set of node and tip numbers for the nodes and tips descended from node
in a vector, or for getParent
the single node preceding node
in the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes the set of extant or extinct tips from a phylogenetic tree.
getExtant(tree, tol=1e-8) getExtinct(tree, tol=1e-8)
getExtant(tree, tol=1e-8) getExtinct(tree, tol=1e-8)
tree |
a phylogeny stored as an object of class |
tol |
a tolerance value to account for numerical imprecision. |
The function getExtant
takes a tree as input and returns a vector containing the names of all the tips that have a height above the root that is equal (to a degree of numerical precision determined by tol
) to the height of the highest tip. These tips are presumed to be "extant."
getExtinct
returns the complement.
A vector with the tip names of extant or extinct species in the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes the sister taxon or node.
getSisters(tree, node, mode=c("number","label"))
getSisters(tree, node, mode=c("number","label"))
tree |
object of class |
node |
a node number, tip number, node label, or tip label. |
mode |
an optional string indicating whether to return the node or tip number(s) or the node or tip label(s), if applicable. |
This function takes a tree and node or tip number of label and returns the number or label of the sister or sisters to that node or tip.
If mode="number"
this function returns an integer or vector containing the node number of numbers of the sister node or tip. If mode="label"
then this function returns a list containing up to two vectors: one for the node numbers of labels of sister nodes (if applicable); and the other containing the tip labels of the sister tips.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Gets the states from the nodes or tips of a mapped tree (e.g., make.simmap
).
getStates(tree, type=c("nodes","tips","both"))
getStates(tree, type=c("nodes","tips","both"))
tree |
is a modified object of class |
type |
mode indicating whether to get states at the nodes ( |
A named vector (for "phylo"
) or matrix (for "multiPhylo"
).
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
describe.simmap
, make.simmap
, read.simmap
, sim.history
Adds node labels to a plotted object of class "phylo"
.
labelnodes(text, node=NULL, interactive=TRUE, shape=c("circle","ellipse", "rect"), ...)
labelnodes(text, node=NULL, interactive=TRUE, shape=c("circle","ellipse", "rect"), ...)
text |
text string or vector to be used as labels. |
node |
node numbers (indices) for the labels. |
interactive |
logical value indicating whether or not nodes should be supplied interactively. (I.e., by clicking on the nodes.) |
shape |
shape to plot around the plotted node label(s). |
... |
optional arguments. |
The nodes to be labels can be selected interactively by the user (i.e., by clicking on the corresponding nodes of the plotted tree).
Invisibly returns a vector of the node indices for the labeled nodes.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Ladderizes an object of class "simmap"
.
ladderize.simmap(tree, right=TRUE)
ladderize.simmap(tree, right=TRUE)
tree |
an object of class |
right |
a logical specifying how the tree should be ladderized. |
This function 'ladderizes' an object of class "simmap"
with a mapped discrete character.
For more information see ladderize
.
A ladderized object of class "simmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
transformation of matrixInternal function for phyl.pca
and others.
lambda.transform(lambda, C)
lambda.transform(lambda, C)
lambda |
scalar, usually (but not necessarily) on the interval 0,1. |
C |
matrix probably returned by |
Multiplies the off-diagonals of a square matrix by lambda
and returns the result.
Typically an among-species phylogenetic variance covariance matrix (e.g., vcv.phylo
) in which the off-diagonal elements have been multiplied by lambda
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Likelihood function for joint estimation of Pagel's parameter.
likMlambda(lambda, X, C)
likMlambda(lambda, X, C)
lambda |
scalar, usually on the interval 0,1 (although not required to be). |
X |
data for various continuous character, in the form of a matrix. |
C |
n x n matrix (for n taxa) containing the height above the root for each pair of taxa in the tree (e.g., |
Generally intended to be used internally by other methods that do joint optimization of (e.g.,
phyl.pca
).
The log-likelihood.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Adds tip labels to a plotted tree by drawing curved, bent, or straight linking lines.
linklabels(text,tips,link.type=c("bent","curved","straight"), ...)
linklabels(text,tips,link.type=c("bent","curved","straight"), ...)
text |
text string or vector to be used as labels. |
tips |
node numbers (indices) for the tips to be labeled. |
link.type |
manner in which to draw the linking lines. |
... |
optional arguments, including |
The idea underlying this function is that the user should first plot the tree without tip labels, but set the area of the plotting device to be sufficient to accommodate the tip labels once they have been added. The function then can be called to add tip labels connected by linking lines to the tips of the plotted tree.
This function annotates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
cladelabels
, nodelabels
, tiplabels
Uses ML to place a fossil lineage into a tree using continuous traits following Revell et al. (2015).
locate.fossil(tree, X, ...)
locate.fossil(tree, X, ...)
tree |
an object of class |
X |
a matrix with continuous character data. |
... |
optional arguments including |
Optimized tree as an object of class "phylo"
.
Liam Revell [email protected]
Felsenstein, J. (1981) Maximum likelihood estimation of evolutionary trees from continuous characters. American Journal of Human Genetics, 25, 471-492.
Felsenstein, J. (2002) Quantitative characters, phylogenies, and morphometrics. In: MacLeod, N. and P. Forey (Eds.) Morphology, Shape and Phylogeny (pp. 27-44). Taylor and Francis, London.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., D. L. Mahler, R. G. Reynolds, and G. J. Slater. (2015) Placing cryptic, recently extinct, or hypothesized taxa into an ultrametric phylogeny using continuous, character data: A case study with the lizard Anolis roosevelti. Evolution, 69, 1027-1035.
Uses ML (or REML) to place a recently extinct, cryptic, or missing taxon on an ultrametric (i.e., time-calibrated) phylogeny following Revell et al. (2015).
locate.yeti(tree, X, ...)
locate.yeti(tree, X, ...)
tree |
an object of class |
X |
a matrix with continuous character data. |
... |
optional arguments including: |
Optimized tree as an object of class "phylo"
.
Liam Revell [email protected]
Felsenstein, J. (1981) Maximum likelihood estimation of evolutionary trees from continuous characters. American Journal of Human Genetics, 25, 471-492.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., D. L. Mahler, R. G. Reynolds, and G. J. Slater. (2015) Placing cryptic, recently extinct, or hypothesized taxa into an ultrametric phylogeny using continuous, character data: A case study with the lizard Anolis roosevelti. Evolution, 69, 1027-1035.
Computes the least squares branch lengths conditioned on a topology and distance matrix.
ls.tree(tree, D)
ls.tree(tree, D)
tree |
phylogeny. |
D |
distance matrix. |
Generally intended as a function to be used internally by optim.phylo.ls
.
A tree with branch lengths.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes and visualizes a lineage through time (LTT) plot, and related measures.
ltt(tree, ...) ## S3 method for class 'phylo' ltt(tree, plot=TRUE, drop.extinct=FALSE, log.lineages=TRUE, gamma=TRUE, ...) ## S3 method for class 'multiPhylo' ltt(tree, drop.extinct=FALSE, gamma=TRUE, ...) ## S3 method for class 'simmap' ltt(tree, plot=TRUE, log.lineages=FALSE, gamma=TRUE, ...) ## S3 method for class 'multiSimmap' ltt(tree, gamma=TRUE, ...) gtt(tree, n=100, ...) mccr(obj, rho=1, nsim=100, ...)
ltt(tree, ...) ## S3 method for class 'phylo' ltt(tree, plot=TRUE, drop.extinct=FALSE, log.lineages=TRUE, gamma=TRUE, ...) ## S3 method for class 'multiPhylo' ltt(tree, drop.extinct=FALSE, gamma=TRUE, ...) ## S3 method for class 'simmap' ltt(tree, plot=TRUE, log.lineages=FALSE, gamma=TRUE, ...) ## S3 method for class 'multiSimmap' ltt(tree, gamma=TRUE, ...) gtt(tree, n=100, ...) mccr(obj, rho=1, nsim=100, ...)
tree |
an object of class |
plot |
a logical value indicating whether or not to create LTT plot. |
drop.extinct |
logical value indicating whether or not to drop extinct tips from the tree. |
log.lineages |
logical value indicating whether LTT plot should be on log-linear (default for |
gamma |
logical value indicating whether or not to compute |
n |
for |
obj |
for |
rho |
for |
nsim |
for |
... |
other arguments to be passed to plotting methods. See |
The function ltt
computes LTT plot with extant and extinct lineages, and optionally conducts -test of Pybus & Harvey (2000). The object returned by
ltt
can be plotted or re-plotted using plot
.
For the case in which tree
is an object of class "simmap"
or "multiSimmap"
then the object will contain the number of lineages through time (for each tree, in the case of "multiSimmap"
objects) separated by mapped regimes.
The function gtt
computes the value of Pybus & Harvey's statistic through time by slicing the tree at various points - by default in even intervals from the time above the root at which N = 3 to the present day.
The function mccr
performs the MCCR test of Pybus & Harvey (2000) which takes into account incomplete taxon sampling in computing a P-value of the statistic.
Although it is calculated here, it's unclear how to interpret the -statistic if not all the tips in the tree are contemporaneous.
ltt
returns an object of class "ltt"
which normally includes the following elements:
times |
a vector of branching times. |
ltt |
a vector of lineages, or a matrix of lineages in each state over time for objects of class |
gamma |
optionally, a value for the |
p |
two-tailed P-value for the |
If tree
is an object of class "multiPhylo"
, then an object of class "multiLtt"
is returned consisting of a list of object of class "ltt"
.
gtt
returns an object of class "gtt"
.
mccr
returns of object of class "mccr"
.
Liam Revell [email protected]
Pybus, O. G., and P. H. Harvey (2000) Testing macro-evolutionary models using incomplete molecular phylogenies. Proc. R. Soc. Lond. B, 267, 2267-2272.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## LTT plots set.seed(99) trees<-pbtree(n=100,scale=100,nsim=10) obj<-ltt(trees,plot=FALSE) plot(obj,log="y",log.lineages=FALSE, bty="l") title(main="LTT plots for 10 pure-birth trees", font.main=3) tree<-pbtree(b=1,d=0.25,t=4) obj<-ltt(tree,gamma=FALSE,show.tree=TRUE, bty="l") title(main="LTT plot with superimposed tree", font.main=3) obj ## GTT plot data(anoletree) anole.gtt<-gtt(anoletree,n=40) plot(anole.gtt)
## LTT plots set.seed(99) trees<-pbtree(n=100,scale=100,nsim=10) obj<-ltt(trees,plot=FALSE) plot(obj,log="y",log.lineages=FALSE, bty="l") title(main="LTT plots for 10 pure-birth trees", font.main=3) tree<-pbtree(b=1,d=0.25,t=4) obj<-ltt(tree,gamma=FALSE,show.tree=TRUE, bty="l") title(main="LTT plot with superimposed tree", font.main=3) obj ## GTT plot data(anoletree) anole.gtt<-gtt(anoletree,n=40) plot(anole.gtt)
)% CI for a set of LTTsThis function computes LTT plots for a set of trees & plots a (1-)% CI by various methods. (See
ltt
for more details.)
ltt95(trees, alpha=0.05, log=FALSE, method=c("lineages","times"), mode=c("median","mean"), ...) ## S3 method for class 'ltt95' plot(x, ...)
ltt95(trees, alpha=0.05, log=FALSE, method=c("lineages","times"), mode=c("median","mean"), ...) ## S3 method for class 'ltt95' plot(x, ...)
trees |
is an object of class |
alpha |
confidence level. Defaults to |
log |
logical value indicating whether or not to plot on the semi-log scale. |
method |
plot the CI on the number of lineages given time ( |
mode |
plot the median or mean LTT. |
x |
object of class |
... |
optional arguments to be used by |
This function creates a plot and invisibly returns an object of class "ltt95"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Creates a temporal map on the tree based on limits
provided by the user.
make.era.map(tree, limits, ...)
make.era.map(tree, limits, ...)
tree |
an object of class |
limits |
a vector containing the temporal limits, in time since the root node of the tree, for the mappings. The first number should be |
... |
optional arguments. |
An object of class "simmap"
with the specified eras mapped as different regimes.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
make.simmap
, read.simmap
, plotSimmap
tree<-pbtree(n=1000,scale=100) tree<-make.era.map(tree,c(0,25,50,75)) plot(tree,ftype="off",lwd=1) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
tree<-pbtree(n=1000,scale=100) tree<-make.era.map(tree,c(0,25,50,75)) plot(tree,ftype="off",lwd=1) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Performs stochastic character mapping (Huelsenbeck et al., 2003) using several different alternative methods.
make.simmap(tree, x, model="SYM", nsim=1, ...) simmap(object, ...)
make.simmap(tree, x, model="SYM", nsim=1, ...) simmap(object, ...)
tree |
a phylogenetic tree as an object of class |
x |
a vector containing the tip states for a discretely valued character, or a matrix containing the prior probabilities of tip states in rows and character states as column names. The names (if |
model |
a character string containing the model or a transition model specified in the form of a matrix. See |
nsim |
number of simulations. If |
... |
optional arguments. So far, |
object |
for generic |
For Q="empirical"
, make.simmap
first fits a continuous-time reversible Markov model for the evolution of x
and then simulates stochastic character histories using that model and the tip states on the tree. This is the same procedure that is described in Bollback (2006), except that simulation is performed using a fixed value of the transition matrix, Q, instead of by sampling Q from its posterior distribution.
For Q="mcmc"
, make.simmap
first samples Q nsim
times from the posterior probability distribution of Q using MCMC, then it simulates nsim
stochastic maps conditioned on each sampled value of Q.
For Q
set to a matrix, make.simmap
samples stochastic mappings conditioned on the fixed input matrix.
make.simmap
uses code that has been adapted from ape's function ace
(by Paradis et al.) to perform Felsenstein's pruning algorithm to compute the likelihood.
As of phytools >= 0.2-33 x
can be a vector of states or a matrix containing the prior probabilities of tip states in rows. In this case the column names of x
should contain the states, and the row names should contain the tip names.
Note that there was a small (but potentially significant) bug in how node states were simulated by make.simmap
in versions of phytools <= 0.2-26. Between phytools 0.2-26 and 0.2-36 there was also a bug for asymmetric models of character change (e.g., model="ARD"
). Finally, between phytools 0.2-33 and phytools 0.2-47 there was an error in use of the conditional likelihoods for the root node, which caused the root node of the tree to be sampled incorrectly. Giorgio Bianchini pointed out that in phytools 1.0-1 (and probably prior recent versions) there was an error sampling the state at the root node of the tree based on the input prior (pi
) supplied by a user – except for pi="equal"
(a flat prior, the default) or for a prior distribution in which one or another state was known to be the global root state (e.g., pi=c(1,0)
, pi=c(0,1)
, etc.). All of these issues should be fixed in the current and all later versions.
If tree
is an object of class "multiPhylo"
then nsim
stochastic maps are generated for each input tree.
A object of class "simmap"
or "multiSimmap"
which consists of an object of class "phylo"
(or a list of such objects with class "multiPhylo"
), with the following additional elements:
maps |
a list of named vectors containing the times spent in each state on each branch, in the order in which they occur. |
mapped.edge |
a matrix containing the total time spent in each state along each edge of the tree. |
Q |
the assumed or sampled value of |
logL |
the log-likelihood of the assumed or sampled |
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
FitzJohn, R. G., W. P. Maddison, and S. P. Otto (2009) Estimating trait-dependent speciation and extinction rates from incompletely resolved phylogenies. Systematic Biology, 58, 595-611.
Huelsenbeck, J. P., R. Neilsen, and J. P. Bollback (2003) Stochastic mapping of morphological characters. Systematic Biology, 52, 131-138.
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J. and L. J. Harmon (2022) Phylogenetic Comparative Methods in R. Princeton University Press.
brownie.lite
, brownieREML
, countSimmap
, describe.simmap
, evol.vcv
, plotSimmap
, read.simmap
, write.simmap
## Not run: ## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit model er_model<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## do stochastic mapping sunfish_smap<-simmap(er_model) ## print a summary of the stochastic mapping summary(sunfish_smap) ## plot a posterior probabilities of ancestral states cols<-setNames(c("blue","red"),levels(fmode)) plot(summary(sunfish_smap),colors=cols,ftype="i") legend("topleft",c("non-piscivorous","piscivorous"), pch=21,pt.bg=cols,pt.cex=2) par(mar=c(5.1,4.1,4.1,2.1),las=1) ## plot posterior density on the number of changes plot(density(sunfish_smap),bty="l") title(main="Posterior distribution of changes of each type", font.main=3) ## End(Not run)
## Not run: ## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit model er_model<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## do stochastic mapping sunfish_smap<-simmap(er_model) ## print a summary of the stochastic mapping summary(sunfish_smap) ## plot a posterior probabilities of ancestral states cols<-setNames(c("blue","red"),levels(fmode)) plot(summary(sunfish_smap),colors=cols,ftype="i") legend("topleft",c("non-piscivorous","piscivorous"), pch=21,pt.bg=cols,pt.cex=2) par(mar=c(5.1,4.1,4.1,2.1),las=1) ## plot posterior density on the number of changes plot(density(sunfish_smap),bty="l") title(main="Posterior distribution of changes of each type", font.main=3) ## End(Not run)
Calculates the similarity of two different stochastically mapped character histories.
map.overlap(tree1, tree2, tol=1e-6, ...) Map.Overlap(tree1, tree2, tol=1e-06, standardize=TRUE, ...)
map.overlap(tree1, tree2, tol=1e-6, ...) Map.Overlap(tree1, tree2, tol=1e-06, standardize=TRUE, ...)
tree1 |
an object of class |
tree2 |
an object of class |
tol |
an optional tolerance value. |
standardize |
for |
... |
optional arguments, such as |
map.overlap
computes a single quantity giving the overall similarity of the maps, consequently this measure only makes sense of some or all of the states are shared between the two mapped tress.
In Map.Overlap
what is computed instead is a matrix in which the rows correspond to the states observed in tree1
and the columns give the states for tree2
, with the numerical values of the matrix showing the total overlap between each pair of mapped states on the two trees.
A numerical value on the interval (0, 1), for map.overlap
; or a matrix whose elements should sum to 1.0 (Map.Overlap
).
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
map.to.singleton
takes an object of class "simmap"
with a mapped discrete character and converts it to a tree with singleton nodes, in which edge has only one state.
map.to.singleton(tree) plotTree.singletons(tree) ## S3 method for class 'singleton' drop.tip(phy, tip, ...) rootedge.to.singleton(tree)
map.to.singleton(tree) plotTree.singletons(tree) ## S3 method for class 'singleton' drop.tip(phy, tip, ...) rootedge.to.singleton(tree)
tree |
an object of class |
phy |
for |
tip |
for |
... |
optional arguments for |
The states for each edge are stored in names(tree$edge.length)
. In a sense this is just an alternative way to use the general structure of the "phylo"
object to encode a tree with a mapped character.
plotTree.singletons
plots a tree with singleton nodes. Note that plotTree
and plot.phylo
now have no trouble graphing trees with singleton nodes - but they do this by just ignoring the singletons. plotTree.singletons
marks the singletons as nodes on the plotted phylogeny.
drop.tip.singleton
drops tips from the tree leaving ancestral nodes for all remaining tips as singletons.
Finally, rootedge.to.singleton
converts a tree with a root edge to a tree with a singleton node instead.
An object of class "phylo"
with singleton nodes. plotTree.singletons
graphs a tree in which the singleton nodes are shown.
If names(tree$edge.length)!=NULL
plotTree.singletons
will use a different color from palette
for each mapped state.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
collapse.singles
, drop.tip
, make.simmap
Computes and orders a vector, matrix, or list of the unique mapped states on a tree or state of trees of class "simmap"
or "multiSimmap"
.
mapped.states(tree, ...)
mapped.states(tree, ...)
tree |
a single tree or a set of trees as an object of class |
... |
optional arguments. |
A vector, matrix, or list.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Adds the reconstructed changes to a plotted tree with a stochastically mapped discrete character.
markChanges(tree, colors=NULL, cex=1, lwd=2, plot=TRUE)
markChanges(tree, colors=NULL, cex=1, lwd=2, plot=TRUE)
tree |
an object of class |
colors |
a named vector of colors used to plot the stochastically mapped character on the tree. |
cex |
expansion factor for line height. |
lwd |
line width. |
plot |
logical value indicating whether the changes should be plotted or not. |
This function returns (invisibly) a matrix containing the x & y coordinates of the marked changes on the plotted tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit model er_model<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## generate single stochastic map sunfish_smap<-simmap(er_model,nsim=1) ## plot stochastic map & mark changes cols<-setNames(c("blue","red"),levels(fmode)) plot(sunfish_smap,cols,ftype="i") markChanges(sunfish_smap,colors=cols,lwd=6) par(mar=c(5.1,4.1,4.1,2.1))
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## fit model er_model<-fitMk(sunfish.tree,fmode,model="ER", pi="fitzjohn") ## generate single stochastic map sunfish_smap<-simmap(er_model,nsim=1) ## plot stochastic map & mark changes cols<-setNames(c("blue","red"),levels(fmode)) plot(sunfish_smap,cols,ftype="i") markChanges(sunfish_smap,colors=cols,lwd=6) par(mar=c(5.1,4.1,4.1,2.1))
This function returns a matrix in which the first column contains all of the internal nodes of tr1
and the second column contains the matching nodes from tr2
, inasmuch as they can be identified.
matchNodes(tr1, tr2, method=c("descendants","distances"), ...) matchLabels(tr1, tr2)
matchNodes(tr1, tr2, method=c("descendants","distances"), ...) matchLabels(tr1, tr2)
tr1 |
first tree. |
tr2 |
second tree. |
method |
method to use to match nodes between trees. |
... |
optional arguments which may or may not be used depending on the value of |
For method="descendants"
, pairs of matching nodes are defined by sharing all descendant leaves in common.
For method="distances"
, nodes are considered to matched if the share the same set of distances (or proportional distances, for optional argument corr=TRUE
) to all tips.
matchLabels
is functionally equivalent but matches node (tip) indices based on identifying matching in the labels only.
A matrix in which the first column contains the nodes of tr1
with the second column containing matching nodes in tr2
, with the criterion for matching defined by method
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Merges two or mapped states on the tree to get one new state.
mergeMappedStates(tree, old.states, new.state)
mergeMappedStates(tree, old.states, new.state)
tree |
an object of class |
old.states |
states to merge. |
new.state |
name for new state. |
mergeMappedStates
can be used to merge two or more mapped states into a single, new state. For instance, one could merge the states "C"
, "G"
, and "T"
and define the new the state "not-A"
.
An object of class "simmap"
or "multiSimmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
These functions midpoint root a rooted or unrooted tree (Farris 1972).
midpoint_root(tree) ## S3 method for class 'root' midpoint(tree, node.labels="support", ...)
midpoint_root(tree) ## S3 method for class 'root' midpoint(tree, node.labels="support", ...)
tree |
an object of class |
node.labels |
argument to be passed to |
... |
optional arguments to be passed to |
Midpoint rooting involves locating the midpoint of the longest path between any two tips and putting the root in that location.
The function midpoint_root
performs the same operation as midpoint
in the phangorn package, but uses no phangorn (Schliep, 2011) code internally.
The function midpoint.root
is a pseudo S3 method for the object class "root"
that exists because when midpoint
was created in phangorn it was not defined as a generic method. This function merely points to midpoint
and is being deprecated out.
An object of class "phylo"
containing a rooted phylogenetic tree.
Liam Revell [email protected]
Farris, J. (1972) Estimating phylogenetic trees from distance matrices. American Naturalist, 106, 645-667.
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Schliep K. P. (2011) phangorn: phylogenetic analysis in R. Bioinformatics, 27, 592-593.
Rotates all the nodes of the tree to try and minimize the different between the order of the tips and the rank-order of a numeric vector x
or (in the case of tipRotate
) the actual integer vector, x
.
minRotate(tree, x, ...) tipRotate(tree, x, ...)
minRotate(tree, x, ...) tipRotate(tree, x, ...)
tree |
tree. |
x |
numeric vector. |
... |
optional arguments to be used by |
Both minRotate
and tipRotate
are designed primarily to be used internally by other phytools functions and particularly by phylo.to.map
(in the case of minRotate
) and by cophylo
(in the case of tipRotate
).
A node-rotated object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function takes a phylogenetic tree and a list of splits and identifies the split with the smallest summed or summed squared distances to all the other splits.
minSplit(tree, split.list, method="sum", printD=FALSE)
minSplit(tree, split.list, method="sum", printD=FALSE)
tree |
an object of class |
split.list |
either a matrix with two named columns, |
method |
an optional string indicating the criterion to minimize: options are |
printD |
logical specifying whether to print distances to screen ( |
A list with the following elements:
node |
node for the minimum split. |
bp |
location on the branch leading to |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., D. L. Mahler, P. Peres-Neto, and B. D. Redelings (2012) A new method for identifying exceptional phenotypic diversification. Evolution, 66, 135-146.
evol.rate.mcmc
, posterior.evolrate
Computes modified Grafen (1989) edge lengths.
modified.Grafen(tree, power=2) node.paths(tree, node)
modified.Grafen(tree, power=2) node.paths(tree, node)
tree |
object of class |
power |
power to raise the depths of each node (in nodes). |
node |
node number for |
This function computes modified Grafen edge lengths in which the length of the edge is determined not by the number of descendant leaves, but instead by the maximum number of node lengths in the path from the node to any leaf.
node.paths
is used internally by modified.Grafen
and computes the set of paths from a node to all tips descended from that node.
An object of class "phylo"
with edge lengths.
Liam Revell [email protected]
Grafen, A. (1989) The phylogenetic regression. Philosophical Transactions of the Royal Society of London. Series B. Biological Sciences, 326, 119-157.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function estimates the MRP (matrix representation parsimony) supertree from a set of input trees (Baum 1992; Ragan 1992).
mrp.supertree(trees, method=c("pratchet","optim.parsimony"), ...) compute.mr(trees, type=c("phyDat","matrix"))
mrp.supertree(trees, method=c("pratchet","optim.parsimony"), ...) compute.mr(trees, type=c("phyDat","matrix"))
trees |
an object of class |
method |
an argument specifying whether to optimize the tree using the phangorn parsimony optimizer |
type |
for |
... |
optional arguments - mostly to be passed to |
mrp.supertree
uses pratchet
or optim.parsimony
from the phangorn package (Schliep, 2011) for optimization, and prop.part
from ape package (Paradis et al. 2004).
See pratchet
or optim.parsimony
for optional arguments, which vary slightly depending on the method. All optional arguments of these methods are available to the user with one exception. The argument tree
in optim.parsimony
is supplied instead as start
. In addition to being an object of class "phylo"
, start
can also be assigned the string values of "NJ"
or "random"
, in which case either a neighbor-joining or random tree will be used as the starting tree for optimization.
The function compute.mr
computes the matrix-representation matrix of the input trees. It is used internally by mrp.supertree
, but can also be used to export an object that can be written to file if desired.
An object of class "phylo"
or "multiPhylo"
that is the MP or set of MP MRP trees.
In the case of compute.mr
, an object of class "phyDat"
or a matrix.
Liam Revell [email protected]
Baum, B. R., (1992) Combining trees as a way of combining data sets for phylogenetic inference, and the desirability of combining gene trees. Taxon, 41, 3-10.
Felsenstein, J. (2004) Inferring Phylogenies. Sinauer.
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Ragan, M. A. (1992) Phylogenetic inference based on matrix representation of trees. Molecular Phylogenetics and Evolution, 1, 53-58.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Schliep, K. P. (2011) phangorn: phylogenetic analysis in R. Bioinformatics, 27, 592-593.
exhaustiveMP
, optim.parsimony
, pratchet
This function conducting a multiple matrix regression (partial Mantel test) and uses Mantel (1967) permutations to test the significance of the model and individual coefficients. It also returns the residual and predicted matrices.
multi.mantel(Y, X, nperm=1000)
multi.mantel(Y, X, nperm=1000)
Y |
single "dependent" square matrix. Can be either a symmetric matrix of class |
X |
a single independent matrix or multiple independent matrices in a list. As with |
nperm |
number of Mantel permutations to be used to compute a P-value of the test. |
Printing the object to screen will result in a summary of the analysis similar to summary.lm
, but with p-values derived from Mantel permutations.
Methods residuals
and fitted
can be used to return residual and fitted matrices, respectively.
An object of class "multi.mantel"
consisting of the following elements:
r.squared |
multiple R-squared. |
coefficients |
model coefficients, including intercept. |
tstatistic |
t-statistics for model coefficients. |
fstatistic |
F-statistic for the overall model. |
probt |
vector of probabilities, based on permutations, for |
probF |
probability of F, based on Mantel permutations. |
residuals |
matrix of residuals. |
predicted |
matrix of predicted values. |
nperm |
the number of permutations used. |
Liam Revell [email protected]
Mantel, N. (1967) The detection of disease clustering and a generalized regression approach. Cancer Research, 27, 209-220.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes phylogenetic covariance matrices from a "simmap"
object.
multiC(tree, internal=FALSE)
multiC(tree, internal=FALSE)
tree |
an object of class |
internal |
logical value indicating whether or not internal nodes should be returned. |
This function takes a modified "phylo"
object as input and returns a set of so-called phylogenetic covariance matrices (e.g., see vcv.phylo
) as a list: one for each mapped state.
Used internally by multiple phytools functions, such as brownie.lite
.
A list of matrices.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
evolvcv.lite
, read.simmap
, vcvPhylo
, vcv.phylo
Fits a flexible multi-rate Brownian motion evolution model using penalized likelihood.
multirateBM(tree, x, method=c("ML","REML"), optim=c("L-BFGS-B","Nelder-Mead","BFGS","CG"), maxit=NULL, n.iter=1, lambda=1, ...)
multirateBM(tree, x, method=c("ML","REML"), optim=c("L-BFGS-B","Nelder-Mead","BFGS","CG"), maxit=NULL, n.iter=1, lambda=1, ...)
tree |
an object of class |
x |
a named numerical vector. Names should correspond to the species names of |
method |
method of optimization. Currently only |
optim |
optimization routine to be used by |
maxit |
to be passed to |
n.iter |
number of times to reiterate failed optimization. |
lambda |
lambda penalty term. High values of |
... |
optional arguments. |
This function fits a flexible Brownian multi-rate model using penalized likelihood.
The model that is being fit is one in which the rate of Brownian motion evolution itself evolves from edge to edge in the tree under a process of geometric Brownian evolution (i.e., Brownian motion evolution on a log scale).
The penalty term, lambda
, determines the cost of variation in the rate of evolution from branch to branch. If lambda is high, then the rate of evolution will vary relatively little between edges (and in the limiting case converge to the single-rate MLE estimate of the rate). By contrast, if the value of lambda
is set to be low, then the rate of evolution can vary from edge to edge with relatively little penalty.
Decreasing the penalty term, however, is not without cost. As lambda
is decreased towards zero, estimated rates will tend to become less and less accurate.
An object of class "multirateBM"
.
Liam Revell [email protected]
Revell, L. J. (2021) A variable-rate quantitative trait evolution model using penalized-likelihood. PeerJ, 9, e11997.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## Not run: ## load data data(sunfish.tree) data(sunfish.data) ## convert from "simmap" to "phylo" sunfish.tree<-as.phylo(sunfish.tree) ## extract character of interest gw<-setNames(sunfish.data$gape.width, rownames(sunfish.data)) ## run penalized-likelihood optimization ## lambda=0.1 is arbitrary fitBM<-multirateBM(sunfish.tree,gw, lambda=0.01) ## print and plot the results print(fitBM) plot(fitBM,ftype="i",fsize=0.8,lwd=6, outline=TRUE) ## reset par par(mar=c(5.1,4.1,4.1,2.1)) ## End(Not run)
## Not run: ## load data data(sunfish.tree) data(sunfish.data) ## convert from "simmap" to "phylo" sunfish.tree<-as.phylo(sunfish.tree) ## extract character of interest gw<-setNames(sunfish.data$gape.width, rownames(sunfish.data)) ## run penalized-likelihood optimization ## lambda=0.1 is arbitrary fitBM<-multirateBM(sunfish.tree,gw, lambda=0.01) ## print and plot the results print(fitBM) plot(fitBM,ftype="i",fsize=0.8,lwd=6, outline=TRUE) ## reset par par(mar=c(5.1,4.1,4.1,2.1)) ## End(Not run)
Computes the Robinson-Foulds (Robinson & Foulds 1981) distance between a set of trees in an object of class "multiPhylo"
.
multiRF(trees,quiet=FALSE,multi2di=FALSE)
multiRF(trees,quiet=FALSE,multi2di=FALSE)
trees |
object of class |
quiet |
logical argument indicating whether or not to run quietly. (Defaults to |
multi2di |
logical argument indicating whether or not to resolve multifurcating trees. (Defaults to |
Computes the Robinson-Foulds distance between all phylogenies in an object of class "multiPhylo"
. Uses prop.part
internally for most of the heavy lifting.
A matrix containing distances.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Robinson, D. R., Foulds, L. R. (1981) Comparison of phylogenetic trees. Mathematical Biosciences, 53, 131-147.
nodeHeights
computes the height above the root for all nodes in the tree. nodeheight
computes the height above the root for a single node.
nodeHeights(tree, ...) nodeheight(tree, node, ...)
nodeHeights(tree, ...) nodeheight(tree, node, ...)
tree |
a phylogeny as an object of class |
node |
for |
... |
optional arguments - presently only |
The function nodeHeights
also gives a handy way to get the total length of the tree from the root to the highest tip which will be given by max(nodeHeights(tree))
.
Generally speaking, nodeHeights
will be faster if the heights of all or a large proportion of nodes is needed, whereas nodeheight
will be faster if the height of one or a small number of nodes are needed.
Either a matrix of the same dimensions as tree$edge
containing the height above the root of each node in edge
(for nodeHeights
); or a single positive number (for nodeheight
).
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load tree data(vertebrate.tree) ## compute height of all nodes H<-nodeHeights(vertebrate.tree) print(H) ## compute total tree depth max(H)
## load tree data(vertebrate.tree) ## compute height of all nodes H<-nodeHeights(vertebrate.tree) print(H) ## compute total tree depth max(H)
This function adds node, edge, or tip labels to the plotted trees of a "cophylo"
object.
nodelabels.cophylo(..., which=c("left","right")) edgelabels.cophylo(..., which=c("left","right")) tiplabels.cophylo(..., which=c("left","right"))
nodelabels.cophylo(..., which=c("left","right")) edgelabels.cophylo(..., which=c("left","right")) tiplabels.cophylo(..., which=c("left","right"))
... |
arguments to be passed to |
which |
argument indicated which of the two plotted trees (the |
Note that the order of tips, edges, and nodes may be different in the object of class "cophylo"
than they are in the original input trees, particularly if cophylo(...,rotate=TRUE)
was used.
Liam Revell [email protected]
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
cophylo
, edgelabels
, nodelabels
, tiplabels
Phylogenetic inference using the method of least-squares (Cavalli-Sforza & Edwards, 1967).
optim.phylo.ls(D, stree=NULL, set.neg.to.zero=TRUE, fixed=FALSE, tol=1e-10, collapse=TRUE)
optim.phylo.ls(D, stree=NULL, set.neg.to.zero=TRUE, fixed=FALSE, tol=1e-10, collapse=TRUE)
D |
a distance matrix. |
stree |
an optional starting tree for the optimization. |
set.neg.to.zero |
a logical value indicating whether to set negative branch lengths to zero (default |
fixed |
a logical value indicating whether to estimate the topology - if |
tol |
a tolerance value used to assess whether the optimization has converged. |
collapse |
a logical indicating whether to collapse branches with zero length. |
Function uses nni
from the phangorn package (Schliep 2011) to conduct NNIs for topology estimation.
Since topology optimization is performed using NNIs, convergence to the true least-squares topology is not guaranteed. It is consequently probably wise to start with a very good tree - such as a NJ tree.
An object of class "phylo"
that (may be) the least-squares tree with branch lengths; also returns the sum of squares in attr(tree,"Q-score")
.
Liam Revell [email protected]
Cavalli-Sforza, L. L., and A. W. F. Edwards. (1967) Phylogenetic analysis: Models and estimation procedures. American Journal of Human Genetics, 19, 233-257.
Felsenstein, J. (2004) Inferring Phylogenies. Sinauer.
Paradis, E., J. Claude, and K. Strimmer. (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Schliep, K. P. (2011) phangorn: phylogenetic analysis in R. Bioinformatics, 27, 592-593.
Orders the levels of a mapped character to match across trees in a "multiSimmap"
object.
orderMappedEdge(trees, ordering=NULL)
orderMappedEdge(trees, ordering=NULL)
trees |
object of class |
ordering |
ordering for the columns of |
This function takes a an object of class "multiSimmap"
with a mapped discrete character (e.g., see make.simmap
and sorts the columns of each tree$mapped.edge
element to have the same state ordering.
This is handy if we want to, for instance, run brownie.lite
on a set of mapped trees, and then average the fitted parameter values across trees. The function also works for a single tree.
An object of class "simmap"
or (normally) "multiSimmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Paints regimes on a tree to create an object of class "simmap"
with mapped regimes.
paintSubTree(tree, node, state, anc.state="1", stem=FALSE) paintBranches(tree, edge, state, anc.state="1")
paintSubTree(tree, node, state, anc.state="1", stem=FALSE) paintBranches(tree, edge, state, anc.state="1")
tree |
a phylogenetic tree as an object of class |
node |
an integer specifying the node number tipward of which the function should paint the derived state. |
edge |
an integer or vector of integers specifying the node or tip numbers of the edges that should be painted in |
state |
a string (or numeric value) specifying the state to paint on the tree tipward of |
anc.state |
the ancestral state to use; will only be applied if there are presently no character values mapped on the tree. |
stem |
logical or numeric value indicating whether to use the derived state on the stem leading to |
These functions map or "paint" arbitrary (i.e., user-specified) discrete character histories on the tree.
paintSubTree
paints the clade downstream of node
with a particular state; whereas paintBranches
paints only a specified branch.
An object of class "simmap"
that contains the specified paintings as a mapped discrete character.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
make.simmap
, read.simmap
, plotSimmap
, sim.history
Internal function for posterior.evolrate
.
paste.tree(tr1, tr2)
paste.tree(tr1, tr2)
tr1 |
receptor tree. |
tr2 |
donor clade. |
Primarily designed as an internal function for posterior.evolrate
; however, can be used to graft a clade onto a receptor tree at the "sticky tip" labeled with "NA"
.
The donor clade needs to have a root edge, even if it is zero length.
A tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
tr1<-rtree(10) tr2<-rtree(10) tr1$tip.label[1]<-"NA" tr2$root.edge<-0 tr3<-paste.tree(tr1,tr2)
tr1<-rtree(10) tr2<-rtree(10) tr1$tip.label[1]<-"NA" tr2$root.edge<-0 tr3<-paste.tree(tr1,tr2)
This function simulates stochastic birth-death trees.
Simulation can be performed conditioning on n
, on t
, or on both simultaneously. If both, then (for optional argument method="rejection"
) rejection sampling is performed whereby trees are simulated given b
and t
until a tree containing n
taxa is found. The giving-up point can be set using the optional argument max.count
.
Simulations can also be performed in continuous time (the default) or discrete time; the difference being that wait times in the continuous-time simulation come from the exponential distribution; whereas waiting times in discrete-time simulations come from the geometric distribution. In addition, discrete-time simulations allow for the possibility that multiple speciation events can occur at (exactly) the same time, so long as they are on separate branches. Finally, sometimes for stopping criterion n
in discrete-time there will be a number of tips different from n
. This indicates that the last event contained more than one speciation event, and a warning is printed.
method="direct"
is presently experimental. It does not really perform direct sampling; however waiting times & birth or death events are sampled first - with only wait-times consistent with n
and t
being retained. This rejection sampling occurs one layer earlier than for method="rejection"
. This results in a significant (several-fold) speed-up of the code and enables sampling conditioned on n
and t
simultaneously for much higher b
and d
. At the present time, extant.only=TRUE
does not work for this mode, nor does type="discrete"
.
Note that if ape=FALSE
, then the function will run faster, and the tree is theoretically compatible with the ape "phylo"
standard; however some downstream errors with functions such as bind.tree
have been observed.
Lastly, under the taxon number stopping criterion (n
) for a non-zero extinction rate (d>0
) sometimes a tree containing fewer than n
extant tips is returned because it has gone completely extinct before the end of the simulation.
pbtree(b=1, d=0, n=NULL, t=NULL, scale=NULL, nsim=1, type=c("continuous", "discrete"), ...)
pbtree(b=1, d=0, n=NULL, t=NULL, scale=NULL, nsim=1, type=c("continuous", "discrete"), ...)
b |
birth rate or speciation rate for |
d |
death rate or extinction rate for |
n |
desired number of species (i.e., taxa-stop criterion). |
t |
total time for simulation (i.e., time-stop criterion). |
scale |
if set, rescales tree to have total length |
nsim |
number of simulated trees to return. |
type |
string to indicate whether to simulate trees in continuous or discrete time. If the former, then wait times between speciation events are drawn from an exponential distribution; whereas if the latter then wait times comes from a geometric distribution. |
... |
optional arguments including |
Simulate stochastic birth-death trees.
A tree or set of trees as an object of class "phylo"
or "multiPhylo"
, respectively.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## simulate a pure-birth tree with 400 tips ## scaled to a length of 1.0 tree<-pbtree(n=400,scale=1) ## simulate a pure-birth tree conditioning on n & t tt<-log(50)-log(2) tree<-pbtree(n=50,t=tt)
## simulate a pure-birth tree with 400 tips ## scaled to a length of 1.0 tree<-pbtree(n=400,scale=1) ## simulate a pure-birth tree conditioning on n & t tt<-log(50)-log(2) tree<-pbtree(n=50,t=tt)
Phylogenetic regression with within-species sampling error following Ives et al. (2007).
pgls.Ives(tree, X, y, Vx=NULL, Vy=NULL, Cxy=NULL, lower=c(1e-8,1e-8), fixed.b1=NULL) pgls.SEy(model, data, corClass=corBrownian, tree, se=NULL, method=c("REML","ML"), interval=c(0,1000), ...)
pgls.Ives(tree, X, y, Vx=NULL, Vy=NULL, Cxy=NULL, lower=c(1e-8,1e-8), fixed.b1=NULL) pgls.SEy(model, data, corClass=corBrownian, tree, se=NULL, method=c("REML","ML"), interval=c(0,1000), ...)
tree |
a phylogeny as an object of class |
X |
a named vector containing a single independent variable (multiple independent variables to be added in future). |
y |
vector the dependent variable. Can be species means or individual values, as for |
Vx |
sampling variances for |
Vy |
sampling variances for |
Cxy |
sampling covariances between |
lower |
vector specifying the lower bounds for estimation for |
fixed.b1 |
fixed regression slope, |
model |
model to fit. (For |
data |
data frame. (For |
corClass |
correlation structure. (For |
se |
vector of standard errors in y. (For |
method |
optimization method. (For |
interval |
interval over which to perform optimization. (For |
... |
optional arguments. (For |
pgls.Ives
fits the phylogenetic regression model with within-species sampling error following Ives et al. (2007).
pgls.SEy
fits a simpler model in which only sampling error in y
is taken into account. This function uses gls
from the nlme package internally for optimization and returns an object of class "gls"
that is compatible with all methods for that object class.
In the case of pgls.Ives
, only the bivariate regression model is implemented. Note that some problems have been reported with the optimization algorithm for this model, which is simple and thus may fail to find the ML solution.
In the case of pgls.SEy
the user can (theoretically) specify any class of linear model permitted by gls
.
In the case of pgls.Ives
, an object of class "pgls.Ives"
with the following elements:
beta |
a vector or matrix of regression coefficients. |
sig2x |
fitted BM rate for |
sig2y |
fitted BM rate for |
a |
fitted ancestral states for |
logL |
log-likelihood. |
convergence |
a value for convergence. |
message |
a message for convergence. |
In the case of pgls.SEy
, an object of class "gls"
.
Liam Revell [email protected]
Ives, A. R., P. E. Midford, and T. Garland Jr. (2007) Within-species measurement error in phylogenetic comparative methods. Systematic Biology, 56, 252-270.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
brownie.lite
, phylosig
, phyl.resid
Plots a phylogenetic traitgram (Evans et al., 2009).
phenogram(tree, x, fsize=1.0, ftype="reg", colors=NULL, axes=list(), add=FALSE, ...)
phenogram(tree, x, fsize=1.0, ftype="reg", colors=NULL, axes=list(), add=FALSE, ...)
tree |
an object of class |
x |
a vector containing the states at the tips or the states at all the tips and the internal nodes of the tree. |
fsize |
relative font size for tip labels. |
ftype |
font type - options are |
colors |
colors for plotting the mapped character (if available) in |
axes |
list of axis dimensions. Items are |
add |
optional logical value indicating whether to add to an open plot. If |
... |
optional arguments including |
Function plots a traitgram (Evans et al. 2009), that is, a projection of the phylogenetic tree in a space defined by phenotype (on the y axis) and time (on the x). If a discrete character is mapped on the tree this will also be plotted.
For spread.labels=TRUE
numerical optimization is performed to optimize the distribution of the labels vertically, where the solution depends on the vector spread.cost
containing the cost of overlap (first) and the cost of deviation from the vertical position of the tip. Note that because this is done via numerical optimization, plotting may hang briefly while the best solution is found (especially for large trees).
Plots a traitgram, optionally with a mapped discrete character, and (invisibly) returns a matrix containing the coordinates of the plotted tip labels.
Liam Revell [email protected]
Evans, M. E. K., Smith, S. A., Flynn, R. S., Donoghue, M. J. (2009) Climate, niche evolution, and diversification of the "bird-cage" evening primroses (Oenothera, sections Anogra and Kleinia). American Naturalist, 173, 225-240.
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., K. Schliep, E. Valderrama, and J. E. Richardson (2018) Graphs in phylogenetic comparative analysis: Anscombe's quartet revisited. Methods in Ecology and Evolution, 9, 2145-2154.
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## plot traitgram phenogram(mammal.tree,ln.bodyMass,ftype="i", spread.cost=c(1,0),fsize=0.7,color=palette()[4], xlab="time (ma)",ylab="log(body mass)",las=1)
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract character of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ## plot traitgram phenogram(mammal.tree,ln.bodyMass,ftype="i", spread.cost=c(1,0),fsize=0.7,color=palette()[4], xlab="time (ma)",ylab="log(body mass)",las=1)
Phylogenetic canonical correlation analysis, following Revell & Harrison (2008).
phyl.cca(tree, X, Y, lambda=1.0, fixed=TRUE)
phyl.cca(tree, X, Y, lambda=1.0, fixed=TRUE)
tree |
a phylogenetic tree in |
X |
a data matrix with traits in columns. |
Y |
data matrix with traits in columns, to be correlated with |
lambda |
optionally, a (fixed) value for |
fixed |
optionally, a logical value indicating whether or not to estimate |
(Optional) joint optimization of is performed using
optimize
on the interval (0,1).
An object of class "phyl.cca"
containing the following elements:
cor |
canonical correlations. |
xcoef |
coefficients for the canonical variables for |
ycoef |
coefficients for the canonical variables for |
xscores |
matrix with the canonical scores for |
yscores |
matrix with the canonical scores for |
chisq |
vector of |
p |
P-values for the hypothesis test that the ith and all subsequent correlations are zero. |
Liam Revell [email protected]
Revell, L. J., Harrison, A. S. (2008) PCCA: A program for phylogenetic canonical correlation analysis. Bioinformatics, 24, 1018-1020.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Phylogenetic paired t-test following Lindenfors et al. (2010).
phyl.pairedttest(tree, x1, x2=NULL, se1=NULL, se2=NULL, lambda=1.0, h0=0.0, fixed=FALSE, ...)
phyl.pairedttest(tree, x1, x2=NULL, se1=NULL, se2=NULL, lambda=1.0, h0=0.0, fixed=FALSE, ...)
tree |
a phylogeny as an object of class |
x1 |
data vector for first trait, or matrix with two traits in columns. |
x2 |
data vector for second trait (or null if |
se1 |
standard errors for |
se2 |
standard errors for |
lambda |
starting value for Pagel's λ (or fixed value, if |
h0 |
null hypothesis (to be tested) for the mean difference between |
fixed |
logical value specifying whether or not to optimize λ. |
... |
optional arguments. |
This function conducts a phylogenetic paired t-test, roughly following Lindenfors et al. (2010).
This is not a phylogenetic ANOVA, in which we want to compare the means of different sets of species on the tree. Instead, we are interested in the difference between two characters, or two measures of a character within a species, and we want to know if this difference is significantly different from zero controlling for the phylogenetic non-independence of species.
Likelihood optimization is performed using optim
with method="L-BFGS-B"
with box constraints on λ (0,1).
An object of class "phyl.pairedttest"
with the following elements:
dbar |
phylogenetic mean difference. |
se |
standard error of |
sig2 |
estimated evolutionary variance (of the difference). |
lambda |
fitted (or fixed) value of λ. |
logL |
log-likelihood of the fitted model. |
t.dbar |
t-value ( |
P.dbar |
P-value. |
df |
the degrees of freedom. |
h0 |
the null hypothesis that was tested. |
Liam Revell [email protected]
Lindenfors, P., L. J. Revell, and C. L. Nunn (2010) Sexual dimorphism in primate aerobic capacity: A phylogenetic test. J. Evol. Biol., 23, 1183-1194.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
This function performs phylogenetic PCA following Revell (2009).
phyl.pca(tree, Y, method="BM", mode="cov", ...) ## S3 method for class 'phyl.pca' biplot(x, ...) scores(object, ...) ## S3 method for class 'phyl.pca' scores(object, ...) as.princomp(x, ...) as.prcomp(x, ...)
phyl.pca(tree, Y, method="BM", mode="cov", ...) ## S3 method for class 'phyl.pca' biplot(x, ...) scores(object, ...) ## S3 method for class 'phyl.pca' scores(object, ...) as.princomp(x, ...) as.prcomp(x, ...)
tree |
phylogeny as an object of class |
Y |
data matrix with traits in columns. |
method |
method to obtain the correlation structure: can be |
mode |
is the mode for the PCA: can be |
x |
object of class |
object |
object of class |
... |
for S3 plotting method |
If method="lambda"
then will be optimized on the interval (0,1) using
optimize
. Optimization method can be set using the option opt
which can take values "ML"
, "REML"
, or "fixed"
. If the last of these is selected than the user should also specify a value of to use via the argument
lambda
.
S3 methods (print
, summary
, and biplot
) are modified from code provided by Joan Maspons and are based on the same methods for objects of class "prcomp"
. Function biplot
now permits the argument choices
to be supplied, which should be a vector of length two indicated the two PC axes to be plotted.
S3 method scores
extracts or computes (for a matrix of newdata
) PC scores given an object of class "phyl.pca"
.
S3 methods as.prcomp
and as.princomp
convert the object of class "phyl.pca"
to objects of class "prcomp"
and "princomp"
, respectively.
An object of class "phyl.pca"
consisting of a list with some or all of the following elements:
Eval |
diagonal matrix of eigenvalues. |
Evec |
matrix with eigenvectors in columns. |
S |
matrix with scores. |
L |
matrix with loadings. |
lambda |
fitted value of |
logL |
log-likelihood for |
Liam Revell [email protected], Joan Maspons
Revell, L. J. (2009) Size-correction and principal components for interspecific comparative studies. Evolution, 63, 3258-3268.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
phyl.cca
, phyl.resid
, prcomp
, princomp
## load data from Mahler et al. (2010) data(anoletree) data(anole.data) ## run phylogenetic PCA anole.pca<-phyl.pca(anoletree,anole.data) print(anole.pca) ## plot results plot(anole.pca) biplot(anole.pca)
## load data from Mahler et al. (2010) data(anoletree) data(anole.data) ## run phylogenetic PCA anole.pca<-phyl.pca(anoletree,anole.data) print(anole.pca) ## plot results plot(anole.pca) biplot(anole.pca)
Computes the residuals from the phylogenetic regression of multiple y variables (in a matrix) on a single x.
phyl.resid(tree, x, Y, method="BM")
phyl.resid(tree, x, Y, method="BM")
tree |
a phylogenetic tree in |
x |
vector containing the single independent variable (e.g., size), or matrix with multiple independent variables in columns. |
Y |
vector or matrix with one or multiple dependent variables in columns. |
method |
method to obtain the correlation structure: can be |
This function fits one or multiple phylogenetic regressions (depending on the number of columns in Y
) and computes the residuals. Designed for phylogenetic size correction using GLS regression (e.g., Revell 2009).
Optionally fits for each regression model. Likelihood optimization of
is performed for
method=
"lambda"
using optimize
on the interval (0,1).
This function is theoretically redundant with residuals
applied to a "gls"
object class in which the correlation structure is based on corBrownian
or corPagel
; however some users may find this method simpler, and it provides a good way to cross-check your results & make sure that you are using gls
correctly.
A list with the following elements:
beta |
a vector or matrix of regression coefficients. |
resid |
a vector or matrix of residuals for species. |
lambda |
a vector of |
logL |
a vector of log-likelihoods ( |
Liam Revell [email protected]
Revell, L. J. (2009) Size-correction and principal components for interspecific comparative studies. Evolution, 63, 3258-3268.
Revell, L. J. (2010) Phylogenetic signal and linear regression on species data. Methods in Ecology and Evolution, 1, 319-329.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Phylogenetic reduced major axis (RMA) regression.
phyl.RMA(x, y, tree, method="BM", lambda=NULL, fixed=FALSE, h0=1.0) ## S3 method for class 'phyl.RMA' coef(object, ...) ## S3 method for class 'phyl.RMA' plot(x, ...)
phyl.RMA(x, y, tree, method="BM", lambda=NULL, fixed=FALSE, h0=1.0) ## S3 method for class 'phyl.RMA' coef(object, ...) ## S3 method for class 'phyl.RMA' plot(x, ...)
x |
vector with names. In the case of the S3 |
y |
vector with names. |
tree |
a phylogenetic tree in |
method |
method to obtain the correlation structure: can be |
lambda |
value of |
fixed |
logical value indicating whether or not |
h0 |
null hypothesis for |
object |
for |
... |
optional arguments for S3 methods. |
Optionally jointly estimates if
method="lambda"
. Likelihood optimization of is performed using
optimize
on the interval (0,1).
The statistical hypothesis testing is based on Clarke (1980; reviewed in McArdle 1988), which differs from some other implementations of non-phylogenetic major axis regression in R.
Note that some statistician think there is never a condition in which a reduced-major-axis regression is appropriate.
An object of class "phyl.RMA"
consisting of a list with the following elements:
RMA.beta |
a vector of RMA regression coefficients. |
V |
a VCV matrix for the traits. |
lambda |
fitted value of |
logL |
log-likelihood ( |
test |
a vector containing results for hypothesis tests on |
resid |
a vector of residuals for |
Liam Revell [email protected]
Clarke, M. R. B. (1980) The reduced major axis of a bivariate sample. Biometrika, 67, 441-446.
McArdle, B. H. (1988) The structural relationship: Regression in biology. Can. J. Zool., 66, 2329-2339.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
phyl.cca
, phyl.pca
, phyl.resid
## load data from Garland et al. (1992) data(mammal.data) data(mammal.tree) ## pull out & log transform variables lnBodyMass<-setNames(log(mammal.data$bodyMass), rownames(mammal.data)) lnHomeRange<-setNames(log(mammal.data$homeRange), rownames(mammal.data)) ## fit RMA regression & print results fitted.rma<-phyl.RMA(lnBodyMass,lnHomeRange, mammal.tree) print(fitted.rma) ## plot fitted RMA par(las=1,bty="n") plot(fitted.rma,las=1,bty="n")
## load data from Garland et al. (1992) data(mammal.data) data(mammal.tree) ## pull out & log transform variables lnBodyMass<-setNames(log(mammal.data$bodyMass), rownames(mammal.data)) lnHomeRange<-setNames(log(mammal.data$homeRange), rownames(mammal.data)) ## fit RMA regression & print results fitted.rma<-phyl.RMA(lnBodyMass,lnHomeRange, mammal.tree) print(fitted.rma) ## plot fitted RMA par(las=1,bty="n") plot(fitted.rma,las=1,bty="n")
Internal function for phyl.pca
.
phyl.vcv(X, C, lambda)
phyl.vcv(X, C, lambda)
lambda |
value for |
X |
data matrix. |
C |
matrix containing the height above the root of each pair of species in the tree. Typically this will have been produced by calling |
Primarily designed as an internal function for phyl.pca
; phyl.vcv
can be used to compute the phylogenetic trait variance-covariance matrix given a phylogenetic VCV, , and a data matrix.
This function should not be confused with vcv.phylo
in the ape package (although one of the objects returned is the output of vcv.phylo
).
Note that prior to phytools 2.1-0 the matrix X
was not sorted to match the rows of C
since that was assumed to have been done in the function calling phyl.vcv
internally; however, I recently discovered that this had caused the function to be used incorrectly resulting in a paper correction. This is now fixed such that X
is checked for row names and (if present) C
is sorted to match the rows of X
. Hopefully this does not cause any problems for other functions using phyl.vcv
!
A list containing three elements, as follows: C
, the matrix vcv.phylo
transformed by lambda
; R
, the among trait variance-covariance matrix for the data in X
; and alpha
, a vector of ancestral states at the root node of the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Simulation based phylogenetic ANOVA following Garland et al. (1993), with post-hoc tests.
phylANOVA(tree, x, y, nsim=1000, posthoc=TRUE, p.adj="holm")
phylANOVA(tree, x, y, nsim=1000, posthoc=TRUE, p.adj="holm")
tree |
a phylogenetic tree in |
x |
a vector containing the groups. |
y |
a vector containing the response variable (continuously valued). |
nsim |
an integer specifying the number of simulations (including the observed data). |
posthoc |
a logical value indicating whether or not to conduct posthoc tests to compare the mean among groups. |
p.adj |
method to adjust P-values for the posthoc tests to account for multiple testing. Options same as |
This function performs the simulation-based phylogenetic ANOVA of Garland et al. (1993) and (optionally) conducts all posthoc comparisons of means among groups (also obtaining the P-values by phylogenetic simulation).
This function uses a little bit of code from both phy.anova
in the geiger package and pairwise.t.test
.
An object of class "phylANOVA"
containing the following elements:
F |
F from observed data. |
Pf |
P-value for F from simulation. |
T |
matrix of t-values. |
Pt |
matrix of multiple test corrected P-values from posthoc t-tests. |
Liam Revell [email protected]
Garland, T., Jr., A. W. Dickerman, C. M. Janis, & J. A. Jones (1993) Phylogenetic analysis of covariance by computer simulation. Systematic Biology, 42, 265-292.
Harmon, L. J., J. T. Weir, C. D. Brock, R. E. Glor, W. Challenger (2008) GEIGER: investigating evolutionary radiations. Bioinformatics, 24, 129-131.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Multivariate phylogenetic heatmap
plot.
phylo.heatmap(tree, X, fsize=1, colors=NULL, standardize=FALSE, ...)
phylo.heatmap(tree, X, fsize=1, colors=NULL, standardize=FALSE, ...)
tree |
an object of class |
X |
a matrix containing data for multiple continuous characters in which |
fsize |
an integer or vector of length 3 containing the font size for the tip labels, the trait labels, and the legend text. (If a single integer is supplied, then the value will be recycled.) |
colors |
a vector of colors to be passed to |
standardize |
a logical value indicating whether or not to standardize each column of |
... |
optional arguments. So far these include: |
Function creates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data data(anoletree) data(anole.data) ## compute phylogenetic residuals anole.data<-as.matrix(anole.data) anole.resids<-cbind(anole.data[,1], phyl.resid(anoletree,anole.data[,1,drop=FALSE], anole.data[,2:ncol(anole.data)])$resid) colnames(anole.resids)[1]<-"SVL" ## plot phylogenetic heatmap phylo.heatmap(anoletree,anole.resids, split=c(0.7,0.3),fsize=c(0.4,0.8,0.8), standardize=TRUE,pts=FALSE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
## load data data(anoletree) data(anole.data) ## compute phylogenetic residuals anole.data<-as.matrix(anole.data) anole.resids<-cbind(anole.data[,1], phyl.resid(anoletree,anole.data[,1,drop=FALSE], anole.data[,2:ncol(anole.data)])$resid) colnames(anole.resids)[1]<-"SVL" ## plot phylogenetic heatmap phylo.heatmap(anoletree,anole.resids, split=c(0.7,0.3),fsize=c(0.4,0.8,0.8), standardize=TRUE,pts=FALSE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
This function performs phylogenetic multiple imputation using maximum likelihood.
phylo.impute(tree, X, ...)
phylo.impute(tree, X, ...)
tree |
an object of class |
X |
data matrix with species names as row labels. Missing data to be imputed should be coded |
... |
optional arguments. |
This function performs phylogenetic imputation in which the evolution of the characters in X
is assumed to have occurred by correlation multivariate Brownian motion.
Missing values are imputed by maximizing their likelihood jointly with the parameters of the Brownian model. The function evol.vcv
is used internally to compute the likelihood.
Note that the Rphylopars package also does phylogenetic imputation for multivariate trait data and it seems to be much faster.
An object of class "phylo.impute"
consisting of a complete data frame with missing values imputed.
Since optimization is performed numerically using likelihood, a summary of the optimization can be seen by evaluating attr(object,"optim")
, in which object
is of class "phylo.impute"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Project a phylogeny on a geographic map.
phylo.to.map(tree, coords, rotate=TRUE, ...) ## S3 method for class 'phylo.to.map' plot(x, type=c("phylogram","direct"), ...)
phylo.to.map(tree, coords, rotate=TRUE, ...) ## S3 method for class 'phylo.to.map' plot(x, type=c("phylogram","direct"), ...)
tree |
an object of class |
coords |
a matrix containing the latitude (in column 1) and the longitude of all tip species in the tree. The row names should be the same as |
rotate |
a logical value indicating whether or not to rotate nodes of the tree to better match longitudinal positions. |
x |
for |
type |
a string indicating whether to map the tips of the tree onto a geographic map from a square phylogram ( |
... |
various optional arguments. For the function |
phylo.to.map
creates an object of class "phylo.to.map"
and (optionally) plots that object.
plot.phylo.to.map
plots an object of class "phylo.to.map"
in which the tips of the tree point to coordinates on a geographic map.
phylo.to.map
creates an object of class "phylo.to.map"
and (if plot=TRUE
) plots a phylogeny projected onto a geographic map.
plot.phylo.to.map
plots on object of class "phylo.to.map"
.
Liam Revell [email protected]
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## generally recommend using higher resolution map ## e.g., from mapdata package data(tortoise.tree) data(tortoise.geog) tortoise.phymap<-phylo.to.map(tortoise.tree, tortoise.geog,plot=FALSE,direction="rightwards", regions="Ecuador") plot(tortoise.phymap,direction="rightwards",pts=FALSE, xlim=c(-92.25,-89.25),ylim=c(-1.8,0.75),ftype="i", fsize=0.8,lty="dashed",map.bg="lightgreen", colors="slategrey") ## reset margins par(mar=c(5.1,4.1,4.1,2.1))
## generally recommend using higher resolution map ## e.g., from mapdata package data(tortoise.tree) data(tortoise.geog) tortoise.phymap<-phylo.to.map(tortoise.tree, tortoise.geog,plot=FALSE,direction="rightwards", regions="Ecuador") plot(tortoise.phymap,direction="rightwards",pts=FALSE, xlim=c(-92.25,-89.25),ylim=c(-1.8,0.75),ftype="i", fsize=0.8,lty="dashed",map.bg="lightgreen", colors="slategrey") ## reset margins par(mar=c(5.1,4.1,4.1,2.1))
Converts between "phylo"
and "backbonePhylo"
.
phylo.toBackbone(x, trans, ...) backbone.toPhylo(x)
phylo.toBackbone(x, trans, ...) backbone.toPhylo(x)
x |
an object of class |
trans |
data frame containing the attributes necessary to translate a backbone tree to an object of class |
... |
optional arguments. |
Either an object of class "phylo"
or an object of class "backbonePhylo"
, depending on the method.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Primarily an internal function for optim.phylo.ls
, this function creates a design matrix for least squares phylogenetic analysis.
phyloDesign(tree)
phyloDesign(tree)
tree |
phylogenetic tree. |
This function returns a matrix containing the edges in the tree (in columns) and pairs of tip node numbers (in rows). Values in the matrix are either 1
if the edge is on the shortest path between the two tips; and 0
otherwise. Probably do not use unless you know what you're doing.
A matrix.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Project a phylogeny into morphospace.
phylomorphospace(tree, X, A=NULL, label=c("radial","horizontal","off"), control=list(), ...) project.phylomorphospace(tree, X, nsteps=200, sleep=0, direction=c("to","from","both"), ...)
phylomorphospace(tree, X, A=NULL, label=c("radial","horizontal","off"), control=list(), ...) project.phylomorphospace(tree, X, nsteps=200, sleep=0, direction=c("to","from","both"), ...)
tree |
a phylogenetic tree in |
X |
an |
A |
an optional |
label |
string indicating whether to plot the tip labels in the same direction as the terminal edge ( |
control |
a list containing the following optional control parameters: |
nsteps |
for |
sleep |
for |
direction |
for |
... |
optional arguments for plotting, including |
This function creates a phylomorphospace plot (a projection of the tree into morphospace) for two characters following Sidlauskas (2008; Evolution). It will also plot a discrete character mapped on tree.
project.phylomorphospace
animates the phylomorphospace projection.
This function creates a phylomorphospace plot
Liam Revell [email protected]
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-90.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Sidlauskas, B. (2008) Continuous and arrested morphological diversification in sister clades of characiform fishes: A phylomorphospace approach. Evolution, 62, 3135-3156.
## load tree & data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## set colors for mapped discrete character cols<-setNames(c("blue","red"), levels(sunfish.data$feeding.mode)) phylomorphospace(sunfish.tree,sunfish.data[,3:2], colors=cols,bty="l",ftype="off",node.by.map=TRUE, node.size=c(0,1.2),xlab="relative buccal length", ylab="relative gape width") title(main="Phylomorphospace of buccal morphology in Centrarchidae", font.main=3)
## load tree & data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## set colors for mapped discrete character cols<-setNames(c("blue","red"), levels(sunfish.data$feeding.mode)) phylomorphospace(sunfish.tree,sunfish.data[,3:2], colors=cols,bty="l",ftype="off",node.by.map=TRUE, node.size=c(0,1.2),xlab="relative buccal length", ylab="relative gape width") title(main="Phylomorphospace of buccal morphology in Centrarchidae", font.main=3)
Creates a phylomorphospace plot in three dimensions.
phylomorphospace3d(tree, X, A=NULL, label=TRUE, control=list(), method=c("dynamic","static"), ...)
phylomorphospace3d(tree, X, A=NULL, label=TRUE, control=list(), method=c("dynamic","static"), ...)
tree |
a phylogenetic tree in |
X |
an |
A |
an optional |
label |
logical value indicating whether to print tip labels next to terminal nodes in the plot (presently doesn't do anything, but labels can be dropped using |
control |
a list containing the following optional control parameters: |
method |
a string either |
... |
optional arguments to be passed to |
This function creates a phylomorphospace plot for three characters using the 3D visualization package, rgl (if available) or statically, by simulating 3D on a flat graphical device.
This function creates a three dimensional phylomorphospace plot. The function returns a function from spin3d
(for method="dynamic"
); or a series of functions from scatterplot3d
(for method="static"
).
Liam Revell [email protected]
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Sidlauskas, B. (2008) Continuous and arrested morphological diversification in sister clades of characiform fishes: A phylomorphospace approach. Evolution, 62, 3135-3156.
fancyTree
, phenogram
, phylomorphospace
data(anoletree) data(anole.data) anole.pca<-phyl.pca(anoletree,anole.data) ## Not run: phylomorphospace3d(anoletree,scores(anole.pca)[,1:3], control=list(spin=FALSE)) ## End(Not run) par(cex=0.5) phylomorphospace3d(anoletree,scores(anole.pca)[,1:3], method="static",angle=-30) par(cex=1)
data(anoletree) data(anole.data) anole.pca<-phyl.pca(anoletree,anole.data) ## Not run: phylomorphospace3d(anoletree,scores(anole.pca)[,1:3], control=list(spin=FALSE)) ## End(Not run) par(cex=0.5) phylomorphospace3d(anoletree,scores(anole.pca)[,1:3], method="static",angle=-30) par(cex=1)
Calculate phylogenetic signal using two different methods (Pagel, 1999; Blomberg et al., 2003).
phylosig(tree, x, method="K", test=FALSE, nsim=1000, se=NULL, start=NULL, control=list(), niter=10) ## S3 method for class 'phylosig' plot(x, ...)
phylosig(tree, x, method="K", test=FALSE, nsim=1000, se=NULL, start=NULL, control=list(), niter=10) ## S3 method for class 'phylosig' plot(x, ...)
tree |
a phylogenetic tree in |
x |
vector containing values for a single continuously distributed trait. In the case of the |
method |
method to compute signal: can be |
test |
logical indicating whether or not to conduct a hypothesis test of |
nsim |
for |
se |
named vector containing the standard errors for each species. |
start |
vector of starting values for optimization of (respectively) |
control |
list of control parameters for multidimensional optimization, implemented in |
niter |
number of iterations for likelihood optimization of |
... |
optional arguments for |
This function computes phylogenetic signal using two different methods. It can also conduct the hypothesis tests for significant phylogenetic signal, and estimate phylogenetic signal incorporating sampling error following Ives et al. (2007).
optimization is performed using
optimize
with the range of set between 0 and the theoretical upper limit of
(determined by the relative height of the most recent internal node on the tree).
plot.phylosig
creates either a plot of the null distribution of K or a likelihood surface, depending on the value of method
.
The function returns an object of class "phylosig"
. With default arguments (method="K"
, test=FALSE
, and se=NULL
), this will be a single numeric value. Otherwise, if (method="K")
, it will consist of a list with up to the following elements:
K |
value of the K-statistic. |
sig2 |
rate of evolution, |
logL |
log-likelihood, for estimation with sampling error. |
P |
optionally, the P-value from the randomization test. |
If (method="lambda")
, it will be a list with up to the following elements:
lambda |
fitted value of |
sig2 |
rate of evolution, |
logL |
log-likelihood. |
logL0 |
log-likelihood for |
P |
P-value of the likelihood ratio test. |
convergence |
value for convergence, for estimation with sampling error only. (See |
message |
message from |
Liam Revell [email protected]
Blomberg, S. P., T. Garland Jr., and A. R. Ives (2003) Testing for phylogenetic signal in comparative data: Behavioral traits are more labile. Evolution, 57, 717-745.
Ives, A. R., P. E. Midford, and T. Garland Jr. (2007) Within-species variation and measurement error in phylogenetic comparative biology. Systematic Biology, 56, 252-270.
Pagel, M. (1999) Inferring the historical patterns of biological evolution. Nature, 401, 877-884.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract characters of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ln.homeRange<-log(setNames(mammal.data$homeRange, rownames(mammal.data))) ## compute phylogenetic signal K K.bodyMass<-phylosig(mammal.tree,ln.bodyMass, test=TRUE) print(K.bodyMass) plot(K.bodyMass) K.homeRange<-phylosig(mammal.tree,ln.homeRange, test=TRUE) print(K.homeRange) plot(K.homeRange) ## compute phylogenetic signal lambda lambda.bodyMass<-phylosig(mammal.tree,ln.bodyMass, method="lambda",test=TRUE) print(lambda.bodyMass) plot(lambda.bodyMass) lambda.homeRange<-phylosig(mammal.tree,ln.homeRange, method="lambda",test=TRUE) print(lambda.homeRange) plot(lambda.homeRange)
## load data from Garland et al. (1992) data(mammal.tree) data(mammal.data) ## extract characters of interest ln.bodyMass<-log(setNames(mammal.data$bodyMass, rownames(mammal.data))) ln.homeRange<-log(setNames(mammal.data$homeRange, rownames(mammal.data))) ## compute phylogenetic signal K K.bodyMass<-phylosig(mammal.tree,ln.bodyMass, test=TRUE) print(K.bodyMass) plot(K.bodyMass) K.homeRange<-phylosig(mammal.tree,ln.homeRange, test=TRUE) print(K.homeRange) plot(K.homeRange) ## compute phylogenetic signal lambda lambda.bodyMass<-phylosig(mammal.tree,ln.bodyMass, method="lambda",test=TRUE) print(lambda.bodyMass) plot(lambda.bodyMass) lambda.homeRange<-phylosig(mammal.tree,ln.homeRange, method="lambda",test=TRUE) print(lambda.homeRange) plot(lambda.homeRange)
Plots a backbone tree (stored as an object of class "backbonePhylo"
) with triangles as subtrees.
## S3 method for class 'backbonePhylo' plot(x, ...)
## S3 method for class 'backbonePhylo' plot(x, ...)
x |
an object of class |
... |
optional arguments. Includes |
Plots a tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## first create our backbone tree with ## random subtree diversities tree<-phytools:::lambdaTree(pbtree(n=10),lambda=0.5) ## create a translation table ## leaving a couple of single-taxon clades for fun tip.label<-sample(tree$tip.label,8) clade.label<-LETTERS[1:8] N<-ceiling(runif(n=8,min=1,max=20)) ## set crown node depth to 1/2 the maximum depth depth<-sapply(tip.label,function(x,y) 0.5*y$edge.length[which(tree$edge[,2]== which(y$tip.label==x))],y=tree) trans<-data.frame(tip.label,clade.label,N,depth) rownames(trans)<-NULL ## here's what trans looks like print(trans) ## convert obj<-phylo.toBackbone(tree,trans) ## plot plot(obj) par(mar=c(5.1,4.1,4.1,2.1)) ## reset par
## first create our backbone tree with ## random subtree diversities tree<-phytools:::lambdaTree(pbtree(n=10),lambda=0.5) ## create a translation table ## leaving a couple of single-taxon clades for fun tip.label<-sample(tree$tip.label,8) clade.label<-LETTERS[1:8] N<-ceiling(runif(n=8,min=1,max=20)) ## set crown node depth to 1/2 the maximum depth depth<-sapply(tip.label,function(x,y) 0.5*y$edge.length[which(tree$edge[,2]== which(y$tip.label==x))],y=tree) trans<-data.frame(tip.label,clade.label,N,depth) rownames(trans)<-NULL ## here's what trans looks like print(trans) ## convert obj<-phylo.toBackbone(tree,trans) ## plot plot(obj) par(mar=c(5.1,4.1,4.1,2.1)) ## reset par
Function plots a tree with branches colored by the value for a quantitative trait or probability, by various methods.
plotBranchbyTrait(tree, x, mode=c("edges","tips","nodes"), palette="rainbow", legend=TRUE, xlims=NULL, ...)
plotBranchbyTrait(tree, x, mode=c("edges","tips","nodes"), palette="rainbow", legend=TRUE, xlims=NULL, ...)
tree |
an object of class |
x |
either a vector of states for the edges, tips, or nodes of the tree (for |
mode |
string indicating plotting mode. |
palette |
color palette to translate character values to color. Options are presently |
legend |
can be a logical value ( |
xlims |
range for the translation map between trait values and the color map. Should be inclusive of all the values in |
... |
other optional arguments to be passed to |
Unlike most other tree plotting functions in phytools, this function calls plot.phylo
(not plotSimmap
) internally.
Note that if prompt=TRUE
, the function will prompt for the position of the legend.
Plots a phylogeny.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Plots one or multiple stochastic character mapped trees.
plotSimmap(tree, colors=NULL, fsize=1.0, ftype="reg", lwd=2, pts=FALSE, node.numbers=FALSE, mar=NULL, add=FALSE, offset=NULL, direction="rightwards", type="phylogram", setEnv=TRUE, part=if(type=="arc") 0.5 else 1.0, xlim=NULL, ylim=NULL, nodes="intermediate", tips=NULL, maxY=NULL, hold=TRUE, split.vertical=FALSE, lend=2, asp=NA, outline=FALSE, plot=TRUE, underscore=FALSE, arc_height=2) ## S3 method for class 'simmap' plot(x, ...) ## S3 method for class 'multiSimmap' plot(x, ...)
plotSimmap(tree, colors=NULL, fsize=1.0, ftype="reg", lwd=2, pts=FALSE, node.numbers=FALSE, mar=NULL, add=FALSE, offset=NULL, direction="rightwards", type="phylogram", setEnv=TRUE, part=if(type=="arc") 0.5 else 1.0, xlim=NULL, ylim=NULL, nodes="intermediate", tips=NULL, maxY=NULL, hold=TRUE, split.vertical=FALSE, lend=2, asp=NA, outline=FALSE, plot=TRUE, underscore=FALSE, arc_height=2) ## S3 method for class 'simmap' plot(x, ...) ## S3 method for class 'multiSimmap' plot(x, ...)
tree |
an object of class |
colors |
a vector with names translating the mapped states to colors - see |
fsize |
relative font size for tip labels. |
ftype |
font type - options are |
lwd |
line width for plotting. |
pts |
logical value indicating whether or not to plot filled circles at each vertex of the tree, as well as at transition points between mapped states. Default is |
node.numbers |
a logical value indicating whether or not node numbers should be plotted. |
mar |
vector containing the margins for the plot to be passed to |
add |
a logical value indicating whether or not to add the plotted tree to the current plot ( |
offset |
offset for the tip labels in character widths. |
direction |
plotting direction. Options are |
type |
plot type. Can be |
setEnv |
logical value indicating whether or not to set the environment |
part |
value between 0 and 1 for |
xlim |
x-limits for the plot. |
ylim |
y-limits for the plot. |
nodes |
node placement following Felsenstein (2004; pp. 574-576). Can be |
tips |
labeled vector containing the vertical position of tips. Normally this will be |
maxY |
maximum value of y to use before rotating a tree into fan configuration. This will only make a difference if different from |
hold |
logical argument indicating whether or not to hold the output to the graphical device before plotting. Defaults to |
split.vertical |
split the color of the vertically plotted edges by the state of the daughter edges. Only applies if the edge state changes exactly at a node. |
lend |
line end style. See |
asp |
aspect ratio. See |
outline |
logical value indicating whether or not to draw a black outline around the plotted edges of the tree. |
plot |
logical value indicating whether or not to actually plot the tree. (See equivalent argument in |
underscore |
logical value indicating whether to plot the underscore character, |
arc_height |
for |
x |
for S3 plotting method, object of class |
... |
for S3 plotting method, other arguments to be passed to |
Plots a tree.
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
Felsenstein, J. (2004) Inferring Phylogenies. Sinauer.
Huelsenbeck, J. P., R. Neilsen, and J. P. Bollback (2003) Stochastic mapping of morphological characters. Systematic Biology, 52, 131-138.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
densityMap
, make.simmap
, read.simmap
data(anoletree) cols<-setNames(c("green","#E4D96F","darkgreen", "brown","black","darkgrey"), c("CG","GB","TC","TG","Tr","Tw")) plot(anoletree,cols,fsize=0.5,ftype="i",outline=TRUE, lwd=3,ylim=c(0,Ntip(anoletree)), mar=c(0.1,0.1,1.1,0.1)) add.simmap.legend(colors=cols,prompt=FALSE,x=0,y=-0.5, vertical=FALSE) title(main="Caribbean ecomorphs of anoles",font.main=3, line=0) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
data(anoletree) cols<-setNames(c("green","#E4D96F","darkgreen", "brown","black","darkgrey"), c("CG","GB","TC","TG","Tr","Tw")) plot(anoletree,cols,fsize=0.5,ftype="i",outline=TRUE, lwd=3,ylim=c(0,Ntip(anoletree)), mar=c(0.1,0.1,1.1,0.1)) add.simmap.legend(colors=cols,prompt=FALSE,x=0,y=-0.5, vertical=FALSE) title(main="Caribbean ecomorphs of anoles",font.main=3, line=0) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Plots estimated posterior probabilities at nodes under the threshold model.
plotThresh(tree, x, mcmc, burnin=NULL, piecol, tipcol="input", legend=TRUE, ...)
plotThresh(tree, x, mcmc, burnin=NULL, piecol, tipcol="input", legend=TRUE, ...)
tree |
phylogenetic tree. |
x |
a named vector containing discrete character states; or a matrix containing the tip species, in rows, and probabilities of being in each state, in columns. |
mcmc |
list object returned by |
burnin |
number of generations (not samples) to exclude as burn in; if |
piecol |
a named vector containing the colors for the posterior probabilities plotted as pie charts at internal nodes. |
tipcol |
a string indicating whether the tip colors should be based on the input data ( |
legend |
logical value or text to be plotted in the legend. |
... |
other arguments to be passed to |
This function uses the object returned by ancThresh
to plot the posterior probabilities of ancestral states under the threshold model.
It is also called internally by ancThresh
.
Plots a tree.
Liam Revell [email protected]
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Essentially a wrapper for plotSimmap
. Arguments in ...
are passed to plotSimmap
, with the exception of optional argument color
which is used to determine the plotted color of the branch lengths of the tree.
plotTree(tree, ...)
plotTree(tree, ...)
tree |
a phylogenetic tree in |
... |
optional arguments. |
Plots a rooted phylogram or cladogram.
This function plots a rooted phylogram or cladogram.
Liam Revell [email protected]
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data(vertebrate.tree) plotTree(vertebrate.tree,fsize=1.2,ftype="i") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
data(vertebrate.tree) plotTree(vertebrate.tree,fsize=1.2,ftype="i") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
plotTree.datamatrix
plots a phylogeny next to a matrix of discrete characters. plotFanTree.wTraits
plots an arc or fan style tree with discrete or continuous data at the tips.
plotTree.datamatrix(tree, X, ...) plotFanTree.wTraits(tree, X, type=c("arc","fan"), ...)
plotTree.datamatrix(tree, X, ...) plotFanTree.wTraits(tree, X, type=c("arc","fan"), ...)
tree |
an object of class |
X |
a data frame with columns as factors for |
type |
plot type for |
... |
optional arguments. |
plotTree.datamatrix
invisibly returns a list containing the font size, a list of the colors used for each column of the plotted data matrix, and the x-coordinate of the rightmost edge of the matrix.
plotFanTree.wTraits
invisibly returns the color palette used for plotting.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
data("liolaemid.data") data("liolaemid.tree") liolaemid.data[liolaemid.tree$tip.label,]->liolaemid.data colors<-list( c("blue","white","red"), terrain.colors(n=10), setNames(c("#F0EAD6","#DF536B"),c("O","V"))) cols<-plotFanTree.wTraits(liolaemid.tree, liolaemid.data[,3:1],lwd=12,colors=colors,ftype="off", spacer=0) legend(x=0,y=0.7*max(nodeHeights(liolaemid.tree)), names(colors[[3]]),lwd=8,col=colors[[3]], title="parity mode",bty="n",xjust=0.5,yjust=0.5) add.color.bar(1.5*max(nodeHeights(liolaemid.tree)),cols[[2]], title="maximum altitude (m)", lims=range(liolaemid.data[,2]),digits=2,prompt=FALSE, x=-0.75*max(nodeHeights(liolaemid.tree)), y=0.2*max(nodeHeights(liolaemid.tree)),subtitle="", lwd=8,outline=FALSE) add.color.bar(1.5*max(nodeHeights(liolaemid.tree)),cols[[1]], title="environmental temp.", lims=range(liolaemid.data[,3]),digits=2,prompt=FALSE, x=-0.75*max(nodeHeights(liolaemid.tree)), y=-0.15*max(nodeHeights(liolaemid.tree)),subtitle="", lwd=8,outline=FALSE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
data("liolaemid.data") data("liolaemid.tree") liolaemid.data[liolaemid.tree$tip.label,]->liolaemid.data colors<-list( c("blue","white","red"), terrain.colors(n=10), setNames(c("#F0EAD6","#DF536B"),c("O","V"))) cols<-plotFanTree.wTraits(liolaemid.tree, liolaemid.data[,3:1],lwd=12,colors=colors,ftype="off", spacer=0) legend(x=0,y=0.7*max(nodeHeights(liolaemid.tree)), names(colors[[3]]),lwd=8,col=colors[[3]], title="parity mode",bty="n",xjust=0.5,yjust=0.5) add.color.bar(1.5*max(nodeHeights(liolaemid.tree)),cols[[2]], title="maximum altitude (m)", lims=range(liolaemid.data[,2]),digits=2,prompt=FALSE, x=-0.75*max(nodeHeights(liolaemid.tree)), y=0.2*max(nodeHeights(liolaemid.tree)),subtitle="", lwd=8,outline=FALSE) add.color.bar(1.5*max(nodeHeights(liolaemid.tree)),cols[[1]], title="environmental temp.", lims=range(liolaemid.data[,3]),digits=2,prompt=FALSE, x=-0.75*max(nodeHeights(liolaemid.tree)), y=-0.15*max(nodeHeights(liolaemid.tree)),subtitle="", lwd=8,outline=FALSE) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margins to default
Plots a tree with error bars around divergence times (nodes).
plotTree.errorbars(tree, CI, ...)
plotTree.errorbars(tree, CI, ...)
tree |
an object of class |
CI |
confidence intervals around internal nodes of the tree, measured in time since the present. |
... |
optional arguments to be passed to |
The matrix CI show contain (in rows) the lower & upper confidence bounds in time since the present.
Optional arguments specific to the error bar plot include gridlines
, bar.lwd
,cex
(for the points plotted at nodes), and bar.col
.
Plots a tree with error bars around internal nodes..
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Plots an upward facing phylogenetic tree with one or more matched lollipop plots. Inspired by a plotting style used by Title et al. (2024).
plotTree.lollipop(tree, x, args.plotTree=list(), args.lollipop=list(), ...)
plotTree.lollipop(tree, x, args.plotTree=list(), args.lollipop=list(), ...)
tree |
an object of class |
x |
a matrix, data frame, or vector of numeric values. |
args.plotTree |
list of arguments to be passed to |
args.lollipop |
list of arguments for the lollipop plot(s). |
... |
optional arguments. |
Creates a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Title, P. O., Singhal, S., Grundler, M. C., Costa, G. C., Pyron, R. A., Colston, T. J., Grundler, M. R., Prates, I., Stepanova, N., Jones, M. E. H., Cavalcanti, L. B. Q., Colli, G. R., Di-Poi, N., Donnellan, S. C., Moritz, C., Mesquita, D. O., Pianka, E. R., Smith, S. A., Vitt, L. J., and Rabosky, D. L. (2024) The macroevolutionary singularity of snakes. Science, 383, 918-923.
phylo.heatmap
, plotTree.barplot
data(anoletree) anole_tree<-as.phylo(anoletree) data(anole.data) anole_data<-cbind(phyl.resid(anole_tree, x=as.matrix(anole.data[,"SVL",drop=FALSE]), Y=as.matrix(anole.data[,c(6,4,2)]))$resid, exp(anole.data[,"SVL",drop=FALSE])) plotTree.lollipop(anole_tree,anole_data, ylab=c("relative (TL)","relative (FLL)", "relative (HL)","SVL")) par(mar=c(5.1,4.1,4.1,2.1))
data(anoletree) anole_tree<-as.phylo(anoletree) data(anole.data) anole_data<-cbind(phyl.resid(anole_tree, x=as.matrix(anole.data[,"SVL",drop=FALSE]), Y=as.matrix(anole.data[,c(6,4,2)]))$resid, exp(anole.data[,"SVL",drop=FALSE])) plotTree.lollipop(anole_tree,anole_data, ylab=c("relative (TL)","relative (FLL)", "relative (HL)","SVL")) par(mar=c(5.1,4.1,4.1,2.1))
Plots a phylogenetic tree with adjacent boxplot or barplot.
plotTree.wBars(tree, x, scale=NULL, width=NULL, type="phylogram", method="plotTree", tip.labels=FALSE, col="grey", border=NULL, ...) plotTree.barplot(tree, x, args.plotTree=list(), args.barplot=list(), ...) plotTree.boxplot(tree, x, args.plotTree=list(), args.boxplot=list(), ...)
plotTree.wBars(tree, x, scale=NULL, width=NULL, type="phylogram", method="plotTree", tip.labels=FALSE, col="grey", border=NULL, ...) plotTree.barplot(tree, x, args.plotTree=list(), args.barplot=list(), ...) plotTree.boxplot(tree, x, args.plotTree=list(), args.boxplot=list(), ...)
tree |
an object of class |
x |
a named vector or matrix of trait values. For |
scale |
scaling factor for the tip bars (relative to the total tree height). If left as |
width |
width of the tip bars. |
type |
plot type. Can be |
method |
plotting method to use. Can be |
tip.labels |
argument indicating whether or not tip labels should be plotted. Defaults to |
col |
colors of the plotted bars. Can be a single value or a vector with length equal to the number of tips in the tree. |
border |
single value specifying the color of the border for the plotted bars. Defaults to |
args.plotTree |
in |
args.barplot |
in |
args.boxplot |
in |
... |
optional arguments to be passed to |
plotTree.wbars
plots a phylogeny in phylogram or fan style with bars at the tips representing the values for a phenotypic trait.
plotTree.barplot
creates a split plot in which a right-facing phylogram is on the left, and a bar plot is shown on the right.
plotTree.boxplot
creates a split plot in which a right-facing phylogram is on the left, and a box plot is shown on the right.
Plots a tree with an associated bar plot for a continuously valued character at the tips.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
barplot
, dotTree
, plotSimmap
, plotTree
## load data from Mahler et al. (2010) data(anoletree) data(anole.data) ## extract overall body size (SVL) svl<-setNames(anole.data$SVL,rownames(anole.data)) ## plotTree.wBars plotTree.wBars(anoletree,svl,type="fan",scal=0.5) par(mar=c(5.1,4.1,4.1,2.1)) ## plotTree.barplot plotTree.barplot(anoletree,exp(svl), args.plotTree=list(fsize=0.5), args.barplot=list(xlab="SVL (mm)")) ## load vertebrate tree and data data(vertebrate.tree) data(vertebrate.data) ## plotTree.barplot options(scipen=4) ## change sci-notation par(cex.axis=0.8) plotTree.barplot(vertebrate.tree, setNames(vertebrate.data$Mass, rownames(vertebrate.data)), args.barplot=list( log="x", xlab="mass (kg)", xlim=c(0.01,500000), col=palette()[4])) options(scipen=0) ## reset par to defaults par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1),cex.axis=1)
## load data from Mahler et al. (2010) data(anoletree) data(anole.data) ## extract overall body size (SVL) svl<-setNames(anole.data$SVL,rownames(anole.data)) ## plotTree.wBars plotTree.wBars(anoletree,svl,type="fan",scal=0.5) par(mar=c(5.1,4.1,4.1,2.1)) ## plotTree.barplot plotTree.barplot(anoletree,exp(svl), args.plotTree=list(fsize=0.5), args.barplot=list(xlab="SVL (mm)")) ## load vertebrate tree and data data(vertebrate.tree) data(vertebrate.data) ## plotTree.barplot options(scipen=4) ## change sci-notation par(cex.axis=0.8) plotTree.barplot(vertebrate.tree, setNames(vertebrate.data$Mass, rownames(vertebrate.data)), args.barplot=list( log="x", xlab="mass (kg)", xlim=c(0.01,500000), col=palette()[4])) options(scipen=0) ## reset par to defaults par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1),cex.axis=1)
Analyzes posterior sample from evol.rate.mcmc
.
posterior.evolrate(tree, ave.shift, mcmc, tips, showTree=FALSE)
posterior.evolrate(tree, ave.shift, mcmc, tips, showTree=FALSE)
tree |
a phylogenetic tree in |
ave.shift |
mean or median shift-point from the posterior sample (see |
mcmc |
matrix |
tips |
list of tips in state |
showTree |
optional logical value indicating whether or not to plot the stretched and shrunken tree generated by the pre-processing algorithm implemented in this function (default is |
This function takes a phylogenetic tree, an average split position, and a raw MCMC output from evol.rate.mcmc
and returns a posterior sample of evolutionary rates rootward () and tipward (
) from the average split.
A matrix containing the posterior sample of evolutionary rates and shift-points between rates.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., D. L. Mahler, P. Peres-Neto, and B. D. Redelings (2012) A new method for identifying exceptional phenotypic diversification. Evolution, 66, 135-146.
Conducts posthoc test.
posthoc(x, ...)
posthoc(x, ...)
x |
an object on which to conduct a post-hoc test. |
... |
optional arguments to be passed to method. |
So far is only implemented for object class "ratebytree"
.
An object of the appropriate class containing the results of a posthoc test.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Print method for an object of class "backbonePhylo"
.
## S3 method for class 'backbonePhylo' print(x, ...)
## S3 method for class 'backbonePhylo' print(x, ...)
x |
an object of class |
... |
optional arguments. |
Prints to screen.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Calculates the parsimony score using the Fitch algorithm.
pscore(tree, x, ...)
pscore(tree, x, ...)
tree |
object of class |
x |
vector (e.g., factor vector), matrix, or data frame. Should contain names or row names. |
... |
optional arguments. |
Mostly for diagnostic purposes. Users interested in using Maximum Parsimony for phylogeny inference or ancestral state reconstruction should refer to the phangorn package.
A numerical value or vector of values.
Liam Revell [email protected]
Felsenstein, J. (2004) Inferring Phylogenies. Sinauer.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## compute the parsimony score pscore(sunfish.tree,fmode)
## load tree and data from Revell & Collar (2009) data(sunfish.tree) data(sunfish.data) ## extract discrete character (feeding mode) fmode<-setNames(sunfish.data$feeding.mode, rownames(sunfish.data)) ## compute the parsimony score pscore(sunfish.tree,fmode)
Statistical test of whether the rate of a continuous character might be influenced by the state of another.
ratebystate(tree, x, y, nsim=100, corr=c("pearson","spearman"), ...)
ratebystate(tree, x, y, nsim=100, corr=c("pearson","spearman"), ...)
tree |
phylogenetic tree. |
x |
a continuous character - the dependent variable in the model. |
y |
a second continuous trait - the response variable. |
nsim |
number of simulations for hypothesis testing. |
corr |
correlation method to use. Same as in |
... |
optional arguments which include |
This function attempts to ask if the rate of a continuous character, y
, depends on the state of a separate continuous trait, x
. This is accomplished by regressing the squared contrasts in y
on the branch or node ancestral estimates of x
.
This function returns an object of class "ratebystate"
with up to the following four elements:
beta |
value of the regression coefficient for square of the contrasts in |
r |
correlation coefficient for |
corr |
string giving the value of |
method |
string giving the value of |
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Multiple methods for comparing the rate or process of evolution between trees.
ratebytree(trees, x, ...) ## S3 method for class 'ratebytree' posthoc(x, ...)
ratebytree(trees, x, ...) ## S3 method for class 'ratebytree' posthoc(x, ...)
trees |
an object of class |
x |
a list of trait vectors for a continuous trait in which the names of each vectors correspond to the tip labels of |
... |
optional arguments, including the argument |
This function essentially implements three different methods for comparing the rate or process of evolution between trees: one for continuously-valued traits, a second for discrete characters, and a third for the rate of diversification (speciation & extinction).
In all cases, the function takes an object of class "multiPhylo"
containing two or more phylogenies (trees
), and (for the first two analyses) a list of trait vectors (x
).
For continuous traits, the function then proceeds to fit two models: one in which the rate (or regime, for models "OU"
and "EB"
) of trait evolution is equal among all trees; and a second in which the rates or regimes can differ between trees.
The latter model corresponds to an extension of the censored approach of O'Meara et al. (2006; Revell et al. 2018) and should also be related to the method of Adams (2012) for comparing rates among traits. See brownie.lite
for a different implementation of the noncensored approach of O'Meara et al. (2006).
For discrete traits, the function instead proceeds to fit two variants of the Mk model (Lewis 2001): one in which the parameters values (transition rates) of the process are free to vary between trees, and a second in which they are fixed to be the same.
For diversification alone, the function fits two different diversification (speciation & extinction) models (Nee et al. 1994; Stadler 2012): one in which the birth (speciation) and death (extinction) rates are identical between the trees, and a second in which they are permitted to differ in various ways depending on the value of "model"
(Revell 2018).
The method posthoc
conducts a post-hoc comparison of parameter estimates between trees in the multi-rate or multi-process model. The parameter that is compared depends on the fitted model. For instance, in model="BM"
posthoc comparison is made of sig2
; if model="OU"
fitted values of alpha
are compared; and so on. The argument p.adjust.method
can be used to specify a method for adjusting P-values for multiple tests following p.adjust
(defaults to p.adjust.method="none"
.
At present it is not possible to specify different models to fit for the different trees - although if (for instance) character evolution on tree 1 proceeded by a strong OU process while character evolution on tree 2 was by BM, we would probably reject a constant-process model and tree 2 should show a very low value of alpha
.
To compute the standard errors for each fitted parameter value, the function computes the negative inverse of the Hessian matrix at the MLEs; however, if this matrix is computationally singular the generalized inverse (ginv
) will be used instead without warning.
The function also conducts a likelihood-ratio test to compare the two models.
For continuous character, optional arguments presently include the following: model
, the model of continuous trait evolution (options are "BM"
, the default, "OU"
, and "EB"
). tol
, used as a minimum value for the fitting rates, to prevent problems in optimization. trace
, a logical value indicating whether or not to report progress in the optimization. test
, the method for hypothesis testing (options are "chisq"
and "simulation"
). quiet
, a logical value indicating whether or not to run perfectly quietly. Finally, se
, a list of vectors containing the standard errors for each value of x
.
For type="discrete"
the optional arguments are slightly different. The argument model
can be used, but it must assume the values "ER"
, "SYM"
, "ARD"
, or a numeric matrix following ace
.
Finally, for type= "diversification"
models are so far "birth-death"
, "equal-extinction"
, and "equal-specation"
, and "Yule"
. It is also important to consider supplying the sampling fractions, rho
, which is a vector of values between 0 and 1 of the same length as trees
. If not provided the method will assume a sampling fraction of 1.0 for all trees - which is seldom true of empirical studies.
An object of class "ratebytree"
or an object of class "posthoc.ratebytree"
in the case of the method posthoc
.
Liam Revell [email protected]
Adams, D. C. (2012) Comparing evolutionary rates for different phenotypic traits on a phylogeny using likelihood. Syst. Biol., 62, 181-192.
Lewis, P. O. (2001) A likelihood approach to estimating phylogeny from discrete morphological character data. Systematic Biology, 50, 913-925.
Nee, S., May, R. M. and Harvey, P. H. (1994) The reconstructed evolutionary process. Philosophical Transactions of the Royal Society of London B, 344, 305-311.
O'Meara, B. C., C. Ane, M. J. Sanderson, and P. C. Wainwright. (2006) Testing for different rates of continuous trait evolution using likelihood. Evolution, 60, 922-933.
Revell, L. J. (2018) Comparing the rates of speciation and extinction between phylogenetic trees. Ecology and Evolution, 8, 5303-5312.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J., Gonzalez-Valenzuela, L. E., Alfonso, A., Castellanos-Garcia, L. A., Guarnizo, C. E., and Crawford, A. J. (2018) Comparing evolutionary rates between trees, clades, & traits. Methods Ecol. Evol., 9, 994-1005.
Stadler, T. (2012) How can we improve the accuracy of macroevolutionary rate estimates? Systematic Biology, 62, 321-329.
Fits a model with one or more temporal rate shifts for a continuous trait on the tree.
rateshift(tree, x, nrates=1, niter=10, method="ML", ...) ## S3 method for class 'rateshift' plot(x, ...) likSurface.rateshift(tree, x, nrates=2, shift.range=NULL, density=20, plot=TRUE, ...)
rateshift(tree, x, nrates=1, niter=10, method="ML", ...) ## S3 method for class 'rateshift' plot(x, ...) likSurface.rateshift(tree, x, nrates=2, shift.range=NULL, density=20, plot=TRUE, ...)
tree |
object of class |
x |
vector of phenotypic trait values for species. |
nrates |
number of rates. |
niter |
number of iterations of optimization routine to ensure convergence. |
method |
optimization method. Can be |
... |
optional arguments. In the case of the |
shift.range |
for |
density |
for |
plot |
logical argument for |
rateshift
attempts to find the location of one or more rate shifts. This model is quite easy to compute the likelihood for, but quite difficult to optimize as the likelihood surface is often rugged. In addition, the model of rateshift
is sometimes non-identifiable, i.e., more than one solution may have the same (maximum) likelihood, depending on the data, the tree, and the number of shifts in our model.
likSurface.rateshift
plots the likelihood surface.
A fitted object of class "rateshift"
, or, in the case of likSurface.rateshift
, a likelihood surface for the shift points.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Revell, L. J. and L. J. Harmon (2022) Phylogenetic Comparative Methods in R. Princeton University Press.
Reads a phylogenetic tree from file.
read.newick(file="", text, ...) readNexus(file="", format=c("standard","raxml"))
read.newick(file="", text, ...) readNexus(file="", format=c("standard","raxml"))
file |
name of text file with single Newick style tree or multiple trees, one per line. For |
text |
character string containing tree. |
format |
file format (source) for |
... |
optional arguments to be passed to |
The function read.newick
reads a simple Newick style tree from file. This function is now almost completely redundant with read.tree
. At the time of development, however, it was more 'robust' than read.tree
in that it didn't fail if the tree contained so-called 'singles' (nodes with only one descendant); however, read.tree
can now handle singleton nodes without difficulty.
The function readNexus
reads a Nexus formatted tree, optionally with bootstrap values as node labels. This function can read a simple Nexus formatted tree from file (like read.nexus
); however, it can also parse the node labels as bootstrap values. This is the output format from the software RAxML. For Nexus tree files with complex node labels (e.g., from the software MrBayes) it will probably fail to parse node labels correctly, if at all.
An object of class "phylo"
, possibly containing singletons (see collapse.singles
); or an object of class "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
tree<-"((Human,Chimp),Gorilla),Monkey);" phy<-read.newick(text=tree)
tree<-"((Human,Chimp),Gorilla),Monkey);" phy<-read.newick(text=tree)
This reads one or multiple SIMMAP style trees from file.
read.simmap(file="", text, format="nexus", rev.order=TRUE, version=1)
read.simmap(file="", text, format="nexus", rev.order=TRUE, version=1)
file |
name of text file with one or multiple SIMMAP v1.0 or v1.5 style trees containing the mapped history of a discrete character. |
text |
character string containing the tree. If |
format |
format of the trees: either |
rev.order |
a logical value indicating whether the states and times along each branch is given (from root to tip) in right-to-left order (if TRUE) or in left-to-right order. If |
version |
version of SIMMAP for input tree. If the tree(s) was/were simulated in SIMMAP v1.0 or written to file by |
This function now accepts trees in both SIMMAP v1.0 and SIMMAP v1.5 format. In addition, it can read a more flexible format than is produced by SIMMAP (for instance, multi-character mapped states and more than 7 mapped states).
The function uses some modified code from read.nexus
from the ape package to read the NEXUS block created by SIMMAP. Also creates the attribute "map.order"
which indicates whether the stochastic map was read in from left to right or right to left. This attribute is used by default by write.simmap
to write the tree in the same order.
An object of class "simmap"
(or list of such objects with class "multiSimmap"
), consisting of a modified object of class "phylo"
with at least the following additional elements:
maps |
a list of named vectors containing the times spent in each state on each branch, in the order in which they occur. |
mapped.edge |
a matrix containing the total time spent in each state along each edge of the tree. |
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
brownie.lite
, evol.vcv
, read.tree
, read.nexus
Function reorders an object of class "backbonePhylo"
.
## S3 method for class 'backbonePhylo' reorder(x, order="cladewise", ...)
## S3 method for class 'backbonePhylo' reorder(x, order="cladewise", ...)
x |
an object of class |
order |
order. See |
... |
optional arguments. |
An object of class "backbonePhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
"simmap"
treeFunction returns a reordered modified "phylo"
object by using reorder.phylo
but then sorting the additional elements $mapped.edge
and $maps
to have the same order as $edge
.
reorderSimmap(tree, order="cladewise", index.only=FALSE, ...)
reorderSimmap(tree, order="cladewise", index.only=FALSE, ...)
tree |
a modified object of class |
order |
|
index.only |
logical value indicating whether only an index should be returned. |
... |
other arguments. |
A modified object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
rep
method for object of class "phylo"
or "multiPhylo"
.
## S3 method for class 'phylo' rep(x, ...) ## S3 method for class 'multiPhylo' rep(x, ...) repPhylo(tree, times)
## S3 method for class 'phylo' rep(x, ...) ## S3 method for class 'multiPhylo' rep(x, ...) repPhylo(tree, times)
tree |
object of class |
times |
number of times to replicate tree. |
x |
for S3 method an object of class |
... |
other arguments for |
repPhylo
is just an alias for rep.phylo
and rep.multiPhylo
.
An object of class "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
tree<-pbtree(n=100) trees<-rep(tree,100)
tree<-pbtree(n=100) trees<-rep(tree,100)
Re-roots a phylogenetic tree at an arbitrary position along an edge.
reroot(tree, node.number, position=NULL, interactive=FALSE, ...)
reroot(tree, node.number, position=NULL, interactive=FALSE, ...)
tree |
a phylogenetic tree in |
node.number |
number of the node descending from the target branch in |
position |
position along the target edge at which to re-root the tree. If not supplied, then the tree will be re-rooted at the node or tip. |
interactive |
logical value indicating whether to use interactive mode (defaults to |
... |
arguments to be passed to |
This function had an error for rootings along edges descended from the root node for phytools<=0.2-47. This should be fixed in the present version. Now uses paste.tree
, root
, and splitTree
internally. Earlier versions also had an error related to node labels. This should be fixed in phytools>=0.4-47.
A phylogenetic tree in "phylo"
format.
Liam Revell [email protected]
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes marginal ancestral states for a discrete character using the re-rooting method of Yang et al. (1995).
In general, this function is redundant with ancr
for circumstances in which it is valid (i.e., symmetric Q matrices), and improper otherwise. In general ancr
should be preferred.
rerootingMethod(tree, x, model=c("ER","SYM"), ...)
rerootingMethod(tree, x, model=c("ER","SYM"), ...)
tree |
an object of class |
x |
a vector of tip values for species, or a matrix containing the prior probability that the tip is in each state. If |
model |
any reversible model. |
... |
optional arguments. Presently the logical argument |
This function uses the re-rooting method of Yang et al. (1995) to get the marginal ancestral state estimates for each internal node of the tree using likelihood. This method get the conditional scaled likelihoods for the root node (which is the same as the marginal ancestral state reconstruction for that node) and successively moves the root to each node in the tree. The function can also return the posterior probabilities for the tip nodes of the tree.
rerootingMethod
calls fitMk
internally. fitMk
uses some code adapted from ace
in the ape package.
An object of class "rerootingMethod"
containing at least the following elements:
loglik |
the log-likelihood. |
Q |
the fitted transition matrix between states. |
marginal.anc |
the marginal ancestral state reconstructions for each node (and, optionally, each tip). |
Liam Revell [email protected]
Paradis, E., J. Claude, and K. Strimmer (2004) APE: Analyses of phylogenetics and evolution in R language. Bioinformatics, 20, 289-290.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Yang, Z., Kumar, S., Nei, M. (1995) A new method of inference of ancestral nucleotide and amino acid sequences. Genetics, 141, 1641-1650.
ace
, ancr
, fitMk
, make.simmap
Generic method for rescaling different types of phylogenetic trees.
rescale(x, ...)
rescale(x, ...)
x |
phylogenetic tree object to be rescaled: e.g., object of class |
... |
other arguments to be used in rescaling, depending on the object class. (E.g., see |
See rescale.phylo
in geiger and rescale.simmap
for details.
A rescaled phylogenetic tree object.
Liam Revell [email protected]
Pennell, M.W., J. M. Eastman, G. J. Slater, J. W. Brown, J. C. Uyeda, R. G. FitzJohn, M. E. Alfaro, and L. J. Harmon (2014) geiger v2.0: an expanded suite of methods for fitting macroevolutionary models to phylogenetic trees. Bioinformatics, 30, 2216-2218.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
"simmap"
Scales a tree with a mapped discrete character ("simmap"
object), or a set of such trees, to an arbitrary total height, preserving the relative time spent in each state along each edge.
## S3 method for class 'simmap' rescale(x, model="depth", ...) ## S3 method for class 'multiSimmap' rescale(x, model="depth", ...) rescaleSimmap(tree, ...)
## S3 method for class 'simmap' rescale(x, model="depth", ...) ## S3 method for class 'multiSimmap' rescale(x, model="depth", ...) rescaleSimmap(tree, ...)
x |
object of class |
model |
model to use to rescale the tree. Currently the only option is |
... |
parameter of the model to use in rescaling. Currently the only parameter is |
tree |
for |
Replaces rescaleTree
(now rescale.phylo
) in the geiger package for the "simmap"
object class. rescaleSimmap
is now a redundant alias for the method rescale.simmap
.
An object of class "simmap"
or "multiSimmap"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load anoletree data(anoletree) ## rescale to have total depth of 50 rescaled_anoletree<-rescale(anoletree,depth=50) ## plot rescaled tree plot(rescaled_anoletree,ftype="i",fsize=0.6, mar=c(5.1,1.1,1.1,1.1)) axis(1,at=seq(0,50,by=10)) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
## load anoletree data(anoletree) ## rescale to have total depth of 50 rescaled_anoletree<-rescale(anoletree,depth=50) ## plot rescaled tree plot(rescaled_anoletree,ftype="i",fsize=0.6, mar=c(5.1,1.1,1.1,1.1)) axis(1,at=seq(0,50,by=10)) par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
Resolves a single multifurcation or all multifurcations in all possible ways.
resolveNode(tree,node) resolveAllNodes(tree)
resolveNode(tree,node) resolveAllNodes(tree)
tree |
an object of class |
node |
for |
This functions resolves a single multifurcation or all multifurcations in a tree in all possible ways. If the input tree has edge lengths, then the resolutions will use internal edges of zero length.
For resolveNode
applied to a multifurcation with n descendants, the number of resolved trees will be equal to the number of possible rooted trees of n taxa. (For instance, three for a trifurcation, 15 for a quadrifurcation, and so on.)
For resolveAllNodes
the number of fully resolved trees will be equal to the product of numbers for resolveNode
applied to each multifurcation separately. (For instance, 45 for a tree containing one trifurcation and one quadrifurcation.)
An object of class "multiPhylo"
- or, if the input tree is already fully resolved, an object of class "phylo"
identical to tree
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
The function rotateNodes
is a simple wrapper for rotate
which rotates a set of nodes or all nodes.
The function rotate.multi
finds all possible rotations around a multifurcating node, given by node
. This will be an object of class "multiPhylo"
, assuming that the node specified is indeed a multifurcation.
The function allRotations
computes all possible rotated trees for a given input phylogeny. For a binary tree, this is generally two raised to the power of the number of internal nodes (so a very large number, if N is even modest in size).
rotateNodes(tree, nodes, polytom=c(1,2), ...) rotate.multi(tree, node) allRotations(tree)
rotateNodes(tree, nodes, polytom=c(1,2), ...) rotate.multi(tree, node) allRotations(tree)
tree |
object of class |
nodes |
either a single node number to rotate, a vector of node numbers, or the string |
polytom |
a vector of mode numeric and length two specifying the two clades that should be exchanged in a polytomy (see |
node |
a single node to rotate (in the case of |
... |
optional arguments. |
All three functions also address the problem that the product of multiple rotations from rotate
can be non-compliant with the implicit "phylo"
standard because the tip numbers in tree$edge
are not in numerical order 1:n
for n
tips.
An object of class "phylo"
(i.e., a phylogenetic tree), in the case of rotateNodes
, or an object of class "multiPhylo"
for rotate.multi
or allRotations
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Rounds the branch lengths of a phylogenetic tree.
roundBranches(tree, digits)
roundBranches(tree, digits)
tree |
an object of class |
digits |
number of digits for rounding. Passed to |
This function rounds the branch lengths of a tree or trees to a precision indicated by digits
, and reconciles any mappings for objects of class "simmap"
or "multiSimmap"
.
An object of class "phylo"
, "multiPhylo"
, "simmap"
, or "multiSimmap"
, with rounded edge lengths.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Plots one or multiple round phylograms, a sigmoidal phylogram or cladogram, or a phylogram draw using cubic splines through the nodes.
roundPhylogram(tree, fsize=1.0, ftype="reg", lwd=2, mar=NULL, offset=NULL, direction="rightwards", type="phylogram", xlim=NULL, ylim=NULL, ...) sigmoidPhylogram(tree, ...) splinePhylogram(tree, ...)
roundPhylogram(tree, fsize=1.0, ftype="reg", lwd=2, mar=NULL, offset=NULL, direction="rightwards", type="phylogram", xlim=NULL, ylim=NULL, ...) sigmoidPhylogram(tree, ...) splinePhylogram(tree, ...)
tree |
an object of class |
fsize |
relative font size for tip labels. |
ftype |
font type - options are |
lwd |
line width for plotting. |
mar |
vector containing the margins for the plot to be passed to |
offset |
offset for the tip labels. |
direction |
plotting direction. Only the option |
type |
plot type. Can be |
xlim |
x-limits for the plot. |
ylim |
y-limits for the plot. |
... |
optional arguments. In the case of |
The underscore character "_"
is automatically swapped for a space in tip labels, as in plotSimmap
.
Plots a tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## load mammal.tree data(mammal.tree) ## plot using roundPhylogram roundPhylogram(compute.brlen(mammal.tree), fsize=0.8,ftype="i") ## load anoletree data(anoletree) ## plot using sigmoidPhylogram sigmoidPhylogram(anoletree,fsize=0.6, ftype="i",direction="upwards") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
## load mammal.tree data(mammal.tree) ## plot using roundPhylogram roundPhylogram(compute.brlen(mammal.tree), fsize=0.8,ftype="i") ## load anoletree data(anoletree) ## plot using sigmoidPhylogram sigmoidPhylogram(anoletree,fsize=0.6, ftype="i",direction="upwards") par(mar=c(5.1,4.1,4.1,2.1)) ## reset margin to default
Internal function for make.simmap
.
rstate(y)
rstate(y)
y |
vector of probabilities. Must have names & should probably add to |
This function picks a random element in a vector according to the probability assigned that element. It returns the name. Uses rmultinom
.
A character or string.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Samples from a set of normal distributions with parameters given in xbar
and xvar
.
sampleFrom(xbar=0, xvar=1, n=1, randn=NULL, type="norm")
sampleFrom(xbar=0, xvar=1, n=1, randn=NULL, type="norm")
xbar |
a named vector of means. |
xvar |
a named vector of variances. |
n |
a vector containing the sample sizes of each species. |
randn |
a range of sample sizes are to be random. |
type |
|
A vector, with labels.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Changes the color map (ramp) in an object of class "contMap"
, "densityMap"
, "phyloScattergram"
, or "multirateBM_plot"
.
setMap(x, ...) ## S3 method for class 'contMap' setMap(x, ...) ## S3 method for class 'densityMap' setMap(x, ...) ## S3 method for class 'phyloScattergram' setMap(x, ...) ## S3 method for class 'multirateBM_plot' setMap(x, ...)
setMap(x, ...) ## S3 method for class 'contMap' setMap(x, ...) ## S3 method for class 'densityMap' setMap(x, ...) ## S3 method for class 'phyloScattergram' setMap(x, ...) ## S3 method for class 'multirateBM_plot' setMap(x, ...)
x |
an object of class |
... |
arguments to be passed to |
An object of class "contMap"
, "densityMap"
, "phyloScattergram"
, or "multirateBM_plot"
.
Liam Revell [email protected]
Revell, L. J. (2012) phytools: An R package for phylogenetic comparative biology (and other things). Methods Ecol. Evol., 3, 217-223.
Revell, L. J. (2013) Two new graphical methods for mapping trait evolution on phylogenies. Methods in Ecology and Evolution, 4, 754-759.
Revell, L. J. (2014) Graphical methods for visualizing comparative data on phylogenies. Chapter 4 in Modern phylogenetic comparative methods and their application in evolutionary biology: Concepts and practice (L. Z. Garamszegi ed.), pp. 77-103.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
contMap
, densityMap
, multirateBM
Simulates multivariate Brownian motion evolution on a tree with multiple evolutionary correlation/covariance matrices.
sim.corrs(tree, vcv, anc=NULL, internal=FALSE)
sim.corrs(tree, vcv, anc=NULL, internal=FALSE)
tree |
an object of class |
vcv |
is a square covariance matrix or named list of matrices (one for each mapped state on the tree). |
anc |
optional vector of values for the root state. |
internal |
logical value indicating whether to return states at internal nodes. |
This function conducts BM simulation on a tree with multiple rates and/or multiple evolutionary correlations between characters.
If vcv
is a single matrix, instead of a list of matrices, sim.corrs
will simulate multivariate BM with a single rate matrix.
A matrix containing the multivariate tip states for the n
species in the tree (and nodes if internal=
TRUE
).
Liam Revell [email protected]
Revell, L. J., and D. C. Collar (2009) Phylogenetic analysis of the evolutionary correlation using likelihood. Evolution, 63, 1090-1100.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
fastBM
, make.simmap
, read.simmap
, sim.history
, sim.rates
Simulates discrete character evolution on a phylogenetic tree.
sim.history(tree, Q, anc=NULL, nsim=1, direction=c("column_to_row","row_to_column"), ...) sim.Mk(tree, Q, anc=NULL, nsim=1, ...) sim.multiMk(tree, Q, anc=NULL, nsim=1, ...)
sim.history(tree, Q, anc=NULL, nsim=1, direction=c("column_to_row","row_to_column"), ...) sim.Mk(tree, Q, anc=NULL, nsim=1, ...) sim.multiMk(tree, Q, anc=NULL, nsim=1, ...)
tree |
a phylogenetic tree as an object of class |
Q |
a matrix containing the instantaneous transition rates between states. Note that for |
anc |
an optional value for the state at the root node; if |
nsim |
number of simulations. |
direction |
row/column direction of the input transition matrix, |
... |
other optional arguments. Currently only |
The function sim.history
simulates a stochastic character history for a discretely valued character trait on the tree. The resultant tree is stored as a modified "phylo"
object in stochastic character map (e.g., make.simmap
) format.
The function sim.Mk
simulates the states for a discrete character at the tips of the tree only.
Finally, the function sim.multiMk
is the same as sim.Mk
except that it permits the user to simulate under different values of Q
in different parts of the tree.
sim.history
returns an object of class "simmap"
(a tree with a mapped discrete character) or "multiSimmap"
for nsim
greater than one.
sim.Mk
and sim.multiMk
return a factor with the states of our discrete character at the tips of the tree only.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
fitMk
, fitmultiMk
, make.simmap
, read.simmap
, plotSimmap
, sim.rates
Simulates two characters under a model in which the rate of one depends on the state of the other.
sim.ratebystate(tree, sig2x=1, sig2y=1, beta=c(0,1), ...)
sim.ratebystate(tree, sig2x=1, sig2y=1, beta=c(0,1), ...)
tree |
phylogenetic tree. |
sig2x |
variance of the Brownian process of evolution for x, |
sig2y |
variance of the Brownian process of evolution for y when |
beta |
intercept and slope of the relationship between the value of x and the Brownian rate in y. |
... |
optional arguments which include |
This function attempts to simulate two characters under a model in which the rate of evolution for the second (y) depends on the states for the first (x).
See ratebystate
for more details.
This function returns a matrix.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Simulates multi-rate or multi-regime continuous trait evolution on a phylogeny.
sim.rates(tree, sig2, anc=0, nsim=1, internal=FALSE, plot=FALSE) multiOU(tree, alpha, sig2, theta=NULL, a0=NULL, nsim=1, internal=FALSE, ...)
sim.rates(tree, sig2, anc=0, nsim=1, internal=FALSE, plot=FALSE) multiOU(tree, alpha, sig2, theta=NULL, a0=NULL, nsim=1, internal=FALSE, ...)
tree |
is a stochastic map format phylogenetic tree in modified |
sig2 |
a named vector containing the rates for each state; names should be states in |
anc |
optional value for the root state. |
nsim |
number of simulations. |
internal |
logical value indicating whether to return states at internal nodes. |
plot |
logical value indicating whether or not to visual the rate heterogeneity (default value is |
alpha |
single value or vector of values of the OU |
theta |
single value or vector of values of the OU |
a0 |
optional value of the root state. Defaults to zero. |
... |
optional arguments. |
The function sim.rates
conducts BM simulation on a tree with multiple rates.
The function multiOU
conducts multi-regime OU simulations on the tree under a range of conditions. multiOU
uses a difference equation approximation of the OU process.
A vector (for nsim=1
) or matrix containing the tip states for the n
species in the tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
fastBM
, make.simmap
, read.simmap
, sim.history
Simulates a discrete time phylogeny and Brownian motion trait, and generates a plot.
simBMphylo(n, t, sig2, plot=TRUE, ...) ## S3 method for class 'simBMphylo' plot(x, ...)
simBMphylo(n, t, sig2, plot=TRUE, ...) ## S3 method for class 'simBMphylo' plot(x, ...)
n |
number of taxa to simulate in the output tree. |
t |
total time for the simulation. |
sig2 |
the rate of evolution under Brownian motion, |
plot |
optional logical value indicating whether or not the simulated object should be plotted. |
... |
optional arguments to be passed to the |
x |
in |
The function simulates a discrete-time pure-birth phylogeny (for fixed N and t using rejection sampling) and then discrete-time Brownian motion on that tree. It then proceeds to generating a plot of the results.
An object of class "simBMphylo"
or a plot.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
set.seed(777) simBMphylo(n=6,t=100,sig2=0.01) ## reset par to defaults par(mfrow=c(1,1)) par(mar=c(5.1,4.1,4.1,2.1))
set.seed(777) simBMphylo(n=6,t=100,sig2=0.01) ## reset par to defaults par(mfrow=c(1,1)) par(mar=c(5.1,4.1,4.1,2.1))
Performs the random skewers matrix comparison method of Cheverud (1996).
skewers(X, Y, nsim=100, method=NULL)
skewers(X, Y, nsim=100, method=NULL)
X |
covariance matrix. |
Y |
covariance matrix. |
nsim |
number of random vectors. |
method |
method to generate a null distribution of the random skewers correlation between matrices. If |
This function performs the random skewers matrix comparison method of Cheverud (1996; also see Cheverud & Marroig 2007 for more details). In addition, it includes a more robust hypothesis test in which random covariance matrices are simulated under a variety of models, and then the mean correlation between response vectors to random skewers are computed.
A list with the following components:
r |
mean random skewers correlation. |
p |
p-value from simulation. |
Liam Revell [email protected]
Cheverud, J. M. (1996) Quantitative genetic analysis of cranial morphology in the cotton-top (Saguinus oedipus) and saddle-back (S. fuscicollis) tamarins. J. Evol. Biol., 9, 5–42.
Cheverud, J. M. and G. Marroig (2007) Comparing covariance matrices: Random skewers method compared to the common principal components model. Genetics & Molecular Biology, 30, 461–469.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Splits the vertical linking-line color on a plotted tree to match the daughter edges.
splitEdgeColor(tree,colors,lwd=2)
splitEdgeColor(tree,colors,lwd=2)
tree |
object of class |
colors |
named vector of colors to be used for plotting. |
lwd |
width of the plotted lines. |
This function splits the vertical line colors to match the daughter edges when the daughters have different states. Mostly to be used with trees generated using paintBranches
or paintSubTree
. Also used internally by plotSimmap
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Plots a tree in two columns or windows.
splitplotTree(tree, fsize=1.0, ftype="reg", lwd=2, split=NULL, new.window=FALSE) plotTree.splits(tree, splits=NULL, file=NULL, fn=NULL, ...)
splitplotTree(tree, fsize=1.0, ftype="reg", lwd=2, split=NULL, new.window=FALSE) plotTree.splits(tree, splits=NULL, file=NULL, fn=NULL, ...)
tree |
an object of class |
fsize |
relative font size for tip labels. |
ftype |
font type - options are |
lwd |
line width for plotting. |
split |
relative vertical position for splitting the tree (between 0 & 1). |
new.window |
whether or not to plot the split tree in a new window. If |
splits |
for |
file |
filename if saving to a PDF file is desired. Otherwise will plot to the default plotting device. |
fn |
function to be executed on each plotted page. For instance, might be: |
... |
other arguments to be passed to |
Plots a tree.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Internal function for posterior.evolrate
.
splitTree(tree, split)
splitTree(tree, split)
tree |
phylogenetic tree. |
split |
split encoded as a list with two elements: |
This function splits the tree at a given point, and returns the two subtrees as an object of class "multiPhylo"
.
Probably do not use this unless you can figure out what you are doing.
Two trees in a list.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Creates a star phylogeny.
starTree(species, branch.lengths=NULL)
starTree(species, branch.lengths=NULL)
species |
a list of species. |
branch.lengths |
an optional list of branch lengths in the same order as |
Creates a star phylogeny with (optionally) user specified branch lengths.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes the Strahler number of all nodes and tips in a phylogenetic tree.
strahlerNumber(tree, plot=TRUE) extract.strahlerNumber(tree, i, plot=TRUE)
strahlerNumber(tree, plot=TRUE) extract.strahlerNumber(tree, i, plot=TRUE)
tree |
an object of class |
i |
order of Strahler number to extract for |
plot |
logical value indicating whether to plot the tree with Strahler numbers for node labels. |
The function strahlerNumber
computes the Strahler number of all nodes and tips in the tree. For more information about Strahler numbers see https://en.wikipedia.org/wiki/Strahler_number. The function extract.strahlerNumber
extracts all of the most inclusive clades of Strahler number i
.
Either a vector with the Strahler number for each tip and internal node; or (for extract.strahlerNumber
the set of (most inclusive) subtrees with Strahler number i
as an object of class "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Fits the threshold model from quantitative genetics to data for two discrete characters or one discrete and one continuous trait, following Felsenstein (2012).
threshBayes(tree, X, types=NULL, ngen=10000, control=list(), ...)
threshBayes(tree, X, types=NULL, ngen=10000, control=list(), ...)
tree |
an object of class |
X |
a matrix or data frame containing values for a discrete character and a continuous character; or two discrete characters. The row names of |
types |
a vector of length |
ngen |
a integer indicating the number of generations for the MCMC. |
control |
a list of control parameters for the MCMC. Control parameters include: |
... |
other optional arguments. The argument |
This function uses Bayesian MCMC to fit the quantitative genetics threshold model (Felsenstein 2012) to data for two discrete characters or one discrete and one continuous character.
The plot
method for the object class can be used to generate a three panel plot showing the likelihood profile, the mean acceptance rates (using a sliding window), and a profile plot for the correlation coefficient, r.
The density
method for the object can be used to plot a posterior density of the correlation coefficient, r. This posterior density is of class "density.threshBayes"
which can also be plotted using an plot
method.
Discrete characters must be binary, but can be coded as any factor.
This function returns an object of class "threshBayes"
consisting of a list with at least the following two elements: par
a matrix containing the posterior sample for the model parameters (evolutionary rates, ancestral states, and correlation); liab
a matrix containing the posterior sample of the liabilities. For continuous characters, the liabilities are treated as known and so the posterior samples are just the observed values.
Liam Revell [email protected]
Felsenstein, J. (2012) A comparative method for both discrete and continuous characters using the threshold model. American Naturalist, 179, 145-156.
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
anc.Bayes
, bmPlot
, evol.rate.mcmc
## Not run: ## load data data(bonyfish.tree) data(bonyfish.data) ## run MCMC mcmc<-threshBayes(bonyfish.tree,bonyfish.data, ngen=100000,plot=FALSE) ## visualize summary of MCMC plot(mcmc) ## reset par par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1)) ## graph posterior density of correlation plot(density(mcmc,bw=0.1)) ## End(Not run)
## Not run: ## load data data(bonyfish.tree) data(bonyfish.data) ## run MCMC mcmc<-threshBayes(bonyfish.tree,bonyfish.data, ngen=100000,plot=FALSE) ## visualize summary of MCMC plot(mcmc) ## reset par par(mfrow=c(1,1),mar=c(5.1,4.1,4.1,2.1)) ## graph posterior density of correlation plot(density(mcmc,bw=0.1)) ## End(Not run)
Computes Deviance Information Criterion from the MCMC object returned by ancThresh
.
threshDIC(tree, x, mcmc, burnin=NULL, sequence=NULL, method="pD")
threshDIC(tree, x, mcmc, burnin=NULL, sequence=NULL, method="pD")
tree |
phylogenetic tree. |
x |
a named vector containing discrete character states; or a matrix containing the tip species, in rows, and probabilities of being in each state, in columns. |
mcmc |
list object returned by |
burnin |
number of generations (not samples) to exclude as burn in; if not supplied then 20% of generations are excluded. |
sequence |
assumed ordering of the discrete character state. If not supplied and |
method |
method for computing the effective number of parameters (options are |
This function computes the Deviance Information Criterion from the MCMC object returned by ancThresh
.
A vector containing the mean deviance and deviance for the parameter means, the effective number of parameters, and the DIC.
Liam Revell [email protected]
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Spiegelhalter, D. J., N. G. Best, B. P. Carlin, and A. Van Der Linde (2002) Bayesian measures of model complexity and fit. Journal of the Royal Statistical Society Series B: Statistical Methodology, 64, 583-639.
Internal function for ancThresh
.
threshState(x, thresholds)
threshState(x, thresholds)
x |
liability. |
thresholds |
a named vector containing the thresholds. |
threshState
can also be used to simulate threshold traits.
A discrete character value.
Liam Revell [email protected]
Revell, L. J. (2014) Ancestral character estimation under the threshold model from quantitative genetics. Evolution, 68, 743-759.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Creates a binary matrix, normally from a factor.
to.matrix(x, seq)
to.matrix(x, seq)
x |
a vector of characters. |
seq |
the sequence for the columns in the output matrix. |
This function takes a vector of characters or a factor and computes a binary matrix.
Primarily designed to be used internally by make.simmap
and rerootingMethod
.
A binary matrix of dimensions length(x)
by length(seq)
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Animates a birth-death tree simulation.
tree.grow(..., res=200, direction="rightwards", ladderize=TRUE)
tree.grow(..., res=200, direction="rightwards", ladderize=TRUE)
... |
arguments to pass to |
res |
number of steps (the resolution of the animation). This also corresponds to the number of frames that will be created if the animation is to be converted to a .gif file. |
direction |
the direction to plot the tree. Only |
ladderize |
logical value indicating whether or not to 'ladderize' the plotted tree. (Defaults to |
This function simulates a birth-death tree under user-defined conditions and then creates an animation of that tree growing from left-to-right in the plotting device, or upwards.
An object of class "phylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
## Not run: ## to create a .gif with ImageMagick installed png(file="pbtree- tree.grow(b=0.06,d=0.02,t=100) dev.off() system("ImageMagick convert -delay 5 -loop 0 *.png pbtree-anim.gif") ## End(Not run)
## Not run: ## to create a .gif with ImageMagick installed png(file="pbtree- tree.grow(b=0.06,d=0.02,t=100) dev.off() system("ImageMagick convert -delay 5 -loop 0 *.png pbtree-anim.gif") ## End(Not run)
Cut (or slice) a phylogenetic tree at a particular time point.
treeSlice(tree, slice, trivial=FALSE, prompt=FALSE, ...)
treeSlice(tree, slice, trivial=FALSE, prompt=FALSE, ...)
tree |
is a phylogenetic tree in |
slice |
a real number indicating the height above the root at which to slice the tree. |
trivial |
a logical value indicating whether or not to return subtrees with a number of tips less than two (default is |
prompt |
logical value indicating whether or not the height of the slice should be given interactively. |
... |
for |
This function slices a tree at a particular height above the root and returns all subtrees or all non-trivial subtrees (i.e., subtrees with more than 1 taxon). Uses extract.clade
in the ape package.
treeSlice
can also be used to crop the terminal fraction of a tree for orientation="rootwards"
.
An object of class "phylo"
or "multiPhylo"
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Attempts to "untangle" the branches of a tree that are tangled when plotting with plot.phylo
, plotTree
, or plotSimmap
.
untangle(tree, method=c("reorder","read.tree"))
untangle(tree, method=c("reorder","read.tree"))
tree |
tree as an object of class |
method |
method to use to attempt to untangle branches. |
Generally speaking, this function is wraps several different internal functions that might be use to fix a badly conformed "phylo"
or "simmap"
object.
An object of class "phylo"
or "simmap"
, depending on the class of tree
.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Computes a phylogenetic variance-covariance matrix.
vcvPhylo(tree, anc.nodes=TRUE, ...)
vcvPhylo(tree, anc.nodes=TRUE, ...)
tree |
object of class |
anc.nodes |
logical value indicating whether or not to include ancestral nodes. |
... |
optional arguments including |
This function returns a so-called phylogenetic variance covariance matrix (e.g., see vcv.phylo
), but (optionally) including ancestral nodes, as well as under multiple evolutionary models.
vcvPhylo
is designed primarily for internal use by other phytools functions.
A matrix.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Writes one or multiple stochastic character mapped trees to file in several formats (following Bollback, 2006).
write.simmap(tree, file=NULL, append=FALSE, map.order=NULL, quiet=FALSE, format="phylip", version=1.0)
write.simmap(tree, file=NULL, append=FALSE, map.order=NULL, quiet=FALSE, format="phylip", version=1.0)
tree |
an object of class |
file |
an optional filename. |
append |
a logical value indicating whether to append to file. |
map.order |
a optional value specifying whether to write the map in left-to-right or right-to-left order. Acceptable values are "left-to-right" or "right-to-left" or some abbreviation of either. If not provided, |
quiet |
logical value indicating whether or not to print a warning message when |
format |
file format for output. |
version |
version of SIMMAP. Note that the options are |
A file.
Liam Revell [email protected]
Bollback, J. P. (2006) Stochastic character mapping of discrete traits on phylogenies. BMC Bioinformatics, 7, 88.
Huelsenbeck, J. P., R. Neilsen, and J. P. Bollback (2003) Stochastic mapping of morphological characters. Systematic Biology, 52, 131-138.
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
make.simmap
, read.simmap
, plotSimmap
This function writes a tree to file with ancestral character states and (optionally) 95% confidence intervals stored as node value.
writeAncestors(tree, Anc=NULL, file="", digits=6, format=c("phylip","nexus"), ...)
writeAncestors(tree, Anc=NULL, file="", digits=6, format=c("phylip","nexus"), ...)
tree |
a phylogenetic tree or set of trees as an object of class |
Anc |
a vector of ancestral states, a list containing the ancestral states and 95% confidence intervals (as from |
file |
an optional string with the filename for output. |
digits |
an integer indicating the number of digits to print for branch lengths and ancestral character values. |
format |
a string indicating whether to output the result in simple Newick (i.e., |
... |
additional arguments including |
A file, string, or vector of strings.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.
Writes one or multiple phylogenetic trees to file in NEXUS format.
Somewhat redundant with write.nexus
.
writeNexus(tree, file="")
writeNexus(tree, file="")
tree |
object of class |
file |
file name for output. |
Trees written to file.
Liam Revell [email protected]
Revell, L. J. (2024) phytools 2.0: an updated R ecosystem for phylogenetic comparative methods (and other things). PeerJ, 12, e16505.