### Bootstrap Example: Neighbor-Joining Source: https://klausvigo.github.io/phangorn/reference/bootstrap.pml.html Demonstrates bootstrapping using the Neighbor-Joining (NJ) method. This example shows how to generate bootstrap trees from phyDat objects and then plot them. ```R data(Laurasiatherian) dm <- dist.hamming(Laurasiatherian) tree <- NJ(dm) # NJ set.seed(123) NJtrees <- bootstrap.phyDat(Laurasiatherian, FUN=function(x)NJ(dist.hamming(x)), bs=100) treeNJ <- plotBS(tree, NJtrees, "phylogram") ``` -------------------------------- ### Example: Visualizing Tree Likelihood Surface Source: https://klausvigo.github.io/phangorn/reference/terraces.html Demonstrates how to use the terraces function with phyDat objects and a combination of pratchet trees and starting trees. ```R data(woodmouse) trs <- pratchet(woodmouse, all=TRUE) start_trs <- get("start_trees", envir = attr(trs, "env")) terraces(as.phyDat(woodmouse), c(trs, start_trs)) ``` -------------------------------- ### Bootstrap Example: Maximum Likelihood Source: https://klausvigo.github.io/phangorn/reference/bootstrap.pml.html Demonstrates bootstrapping with Maximum Likelihood (ML) tree estimation. This example first optimizes a pml object and then performs bootstrap analysis on it. ```R fit <- pml(tree, Laurasiatherian) fit <- optim.pml(fit, rearrangement="NNI") set.seed(123) bs <- bootstrap.pml(fit, bs=100, optNni=TRUE) treeBS <- plotBS(fit$tree,bs) ``` -------------------------------- ### Set Working Directory and Load Example Data Source: https://klausvigo.github.io/phangorn/articles/IntertwiningTreesAndNetworks.html Sets the working directory to the phangorn package's example files and loads DNA matrix, RAxML trees, and MrBayes trees. Use `setwd()` to specify your own file path. ```R ## automatically set the correct working directory for the examples below # setwd(system.file("extdata/trees", package = "phangorn")) # for this vignette we create a path to the files we want to load fdir <- system.file("extdata/trees", package = "phangorn") ## in your case it may look something like this... # setwd("C:/TreesNetworks/Example Files") ##DNA Matrix, maybe not needed woodmouse <- read.phyDat(file.path(fdir,"woodmouse.fasta"),format="fasta") ## RAxML best-known tree with bipartition support (from previous analysis) raxml.tree <- read.tree(file.path(fdir,"RAxML_bipartitions.woodmouse")) ## RAxML bootstrap trees (from previous analysis) raxml.bootstrap <- read.tree(file.path(fdir,"RAxML_bootstrap.woodmouse")) ## MrBayes consensus tree (50% majority rule) (from previous analysis) mrbayes.tree <- read.nexus(file.path(fdir,"woodmouse.mrbayes.nex.con")) ## MrBayes sample runs 1 and 2 (from previous analysis) run1 <- read.nexus(file.path(fdir,"woodmouse.mrbayes.nex.run1.t")) run2 <- read.nexus(file.path(fdir,"woodmouse.mrbayes.nex.run2.t")) ## How many trees are in the MrBayes tree sample? run1 ``` -------------------------------- ### Bootstrap Example: Maximum Parsimony Source: https://klausvigo.github.io/phangorn/reference/bootstrap.pml.html Demonstrates bootstrapping with Maximum Parsimony (MP) tree estimation. This example shows how to estimate MP trees, bootstrap them using `bootstrap.phyDat`, and then plot the results. ```R treeMP <- pratchet(Laurasiatherian) treeMP <- acctran(treeMP, Laurasiatherian) set.seed(123) BStrees <- bootstrap.phyDat(Laurasiatherian, pratchet, bs = 100) treeMP <- plotBS(treeMP, BStrees, "phylogram") add.scale.bar() ``` -------------------------------- ### Bootstrap and UPGMA Example Source: https://klausvigo.github.io/phangorn/reference/densiTree.html This example demonstrates how to generate bootstrap samples from a phylogenetic dataset using `bootstrap.phyDat` and then compute a UPGMA tree for each sample using `upgma` and `dist.hamming`. This is a common preprocessing step before visualizing variation with `densiTree`. ```R data(Laurasiatherian) set.seed(1) bs <- bootstrap.phyDat(Laurasiatherian, FUN = function(x) upgma(dist.hamming(x)), bs=25) ``` -------------------------------- ### Example Usage of codonTest Source: https://klausvigo.github.io/phangorn/reference/codonTest.html Demonstrates how to use the codonTest function with sample data. It includes steps for data preparation, tree building, model fitting, and plotting the results. This example is computationally intensive and marked as dontrun. ```R if (FALSE) { # \dontrun{ # load woodmouse data from ape data(woodmouse) dat_codon <- dna2codon(as.phyDat(woodmouse), code=2) tree <- NJ(dist.ml(dat_codon)) # optimize the model the old way fit <- pml(tree, dat_codon, bf="F3x4") M0 <- optim.pml(fit, model="codon1") # Now using the codonTest function fit_codon <- codonTest(tree, dat_codon) fit_codon plot(fit_codon, "M1a") } # } ``` -------------------------------- ### Example of using write.ancestral with pml_bb and anc_pml Source: https://klausvigo.github.io/phangorn/reference/write.ancestral.html This example demonstrates how to perform a maximum likelihood ancestral reconstruction using `pml_bb` and `anc_pml`, and then export the results using `write.ancestral`. It also shows how to create an ancestral object from external iqtree results and plot it. Finally, it cleans up generated files. ```R data(Laurasiatherian) fit <- pml_bb(Laurasiatherian[,1:100], "JC", rearrangement = "none") anc_ml <- anc_pml(fit) write.ancestral(anc_ml) # Can be also results from iqtree align <- read.phyDat("ancestral_align.fasta", format="fasta") tree <- read.tree("ancestral_tree.nwk") df <- read.table("ancestral_state.tsv", header=TRUE) anc_ml_disc <- as.ancestral(tree, df, align) plotAnc(anc_ml_disc, 20) unlink(c("ancestral_align.fasta", "ancestral_tree.nwk", "ancestral_state.tsv", "ancestral_state.fasta")) ``` -------------------------------- ### Example: Inspecting a phyDat object Source: https://klausvigo.github.io/phangorn/reference/phyDat.html Demonstrates how to load a dataset and inspect its class and summary information as a phyDat object. ```R data(Laurasiatherian) class(Laurasiatherian) #> [1] "phyDat" Laurasiatherian #> 47 sequences with 3179 character and 1605 different site patterns. #> The states are a c g t ``` -------------------------------- ### Random Addition for Starting Tree Source: https://klausvigo.github.io/phangorn/reference/parsimony.html Generates a starting tree using the random addition method with the Laurasiatherian dataset. This can be used as an initial tree for other optimization methods. ```R treeRA <- random.addition(Laurasiatherian) ``` -------------------------------- ### Load example datasets Source: https://klausvigo.github.io/phangorn/articles/Networx.html Loads the Laurasiatherian and yeast datasets for use in phylogenetic analyses. ```R data(Laurasiatherian) data(yeast) ``` -------------------------------- ### Install Optional Packages for Full Functionality Source: https://klausvigo.github.io/phangorn/index.html Installs the rgl and ggseqlogo packages, which may be needed to utilize all functionalities of phangorn. ```r install.packages("rgl") install.packages("ggseqlogo") ``` -------------------------------- ### Install phangorn Development Version from GitHub Source: https://klausvigo.github.io/phangorn/index.html Installs the development version of the phangorn package directly from its GitHub repository. ```r remotes::install_github("KlausVigo/phangorn") ``` -------------------------------- ### SH Test with pmlPart Objects Source: https://klausvigo.github.io/phangorn/reference/SH.test.html Demonstrates using the SH test with an object of class `pmlPart`. This example is part of a larger `dontrun` block, indicating it might be computationally intensive or require specific setup. ```R if (FALSE) { # \dontrun{ example(pmlPart) SH.test(sp, B=1000) } ``` -------------------------------- ### Import Partitioned NEXUS Data Source: https://klausvigo.github.io/phangorn/reference/read.nexus.partitions.html This example demonstrates how to create a NEXUS file with defined character sets and then import it using read.nexus.partitions. It shows how the data is split into different partitions based on the SETS block. ```R tree <- rtree(10) dat <- simSeq(tree, l=24) fcat <- function(..., file = zz) cat(..., file=file, sep="", append=TRUE) zz <- tempfile(pattern="file", tmpdir=tempdir(), fileext=".nex") write.phyDat(dat, file=zz, format="nexus") fcat("BEGIN SETS;\n") fcat(" Charset codon1 = 1-12/3;\n") fcat(" Charset codon2 = 2-12/3;\n") fcat(" Charset codon3 = 3-12/3;\n") fcat(" Charset range = 16-18;\n") fcat(" Charset range2 = 13-15 19-21;\n") fcat(" Charset singles = 22 23 24;\n") fcat("END;\n") tmp <- read.nexus.partitions(zz) tmp #\> $codon1 #\> 10 sequences with 4 character and 4 different site patterns. #\> The states are a c g t #\> #\> $codon2 #\> 10 sequences with 4 character and 4 different site patterns. #\> The states are a c g t #\> #\> $codon3 #\> 10 sequences with 4 character and 4 different site patterns. #\> The states are a c g t #\> #\> $range #\> 10 sequences with 3 character and 3 different site patterns. #\> The states are a c g t #\> #\> $range2 #\> 10 sequences with 6 character and 6 different site patterns. #\> The states are a c g t #\> #\> $singles #\> 10 sequences with 3 character and 3 different site patterns. #\> The states are a c g t #\> unlink(zz) ``` -------------------------------- ### Generate Starting Tree and Optimize Parsimony Source: https://klausvigo.github.io/phangorn/articles/Trees.html Generates a starting tree using random addition and then optimizes it using subtree pruning and regrafting (SPR) for parsimony. Compares parsimony scores of the initial and optimized trees. ```R treeRA <- random.addition(primates) treeSPR <- optim.parsimony(treeRA, primates) parsimony(c(treeRA, treeSPR), primates) ``` ```R ## [1] 753 750 ``` -------------------------------- ### phyDat conversion examples Source: https://klausvigo.github.io/phangorn/reference/as.phyDat.html Demonstrates converting a phyDat object to character and back, and to DNAbin format. ```R data(Laurasiatherian) class(Laurasiatherian) #> [1] "phyDat" Laurasiatherian #> 47 sequences with 3179 character and 1605 different site patterns. #> The states are a c g t # transform as characters LauraChar <- as.character(Laurasiatherian) # and back Laura <- phyDat(LauraChar) all.equal(Laurasiatherian, Laura) #> [1] TRUE LauraDNAbin <- as.DNAbin(Laurasiatherian) all.equal(Laurasiatherian, as.phyDat(LauraDNAbin)) #> [1] TRUE ``` -------------------------------- ### Example for consensusNet Source: https://klausvigo.github.io/phangorn/reference/as.networx.html This code block is a placeholder for demonstrating the usage of consensusNet, as referenced in the documentation. It is intended to be run within a specific context. ```R # also see example in consensusNet example(consensusNet) ``` -------------------------------- ### Compute MAST and return tip labels Source: https://klausvigo.github.io/phangorn/reference/mast.html This example demonstrates how to compute the Maximum Agreement Subtree (MAST) between two phylogenetic trees and retrieve only the tip labels of the MAST. Ensure you have the phangorn package installed and loaded. ```R tree1 <- rtree(100) tree2 <- rNNI(tree1, 20) tips <- mast(tree1, tree2) ``` -------------------------------- ### Example: Plotting trees with FBP and TBE bootstrap values Source: https://klausvigo.github.io/phangorn/reference/plotBS.html Demonstrates how to plot a tree with bootstrap values using both the default FBP method and the TBE method for comparison. ```R fdir <- system.file("extdata/trees", package = "phangorn") # RAxML best-known tree with bipartition support (from previous analysis) raxml.tree <- read.tree(file.path(fdir,"RAxML_bipartitions.woodmouse")) # RAxML bootstrap trees (from previous analysis) raxml.bootstrap <- read.tree(file.path(fdir,"RAxML_bootstrap.woodmouse")) par(mfrow=c(1,2)) plotBS(raxml.tree, raxml.bootstrap, "p") plotBS(raxml.tree, raxml.bootstrap, "p", "TBE") ``` -------------------------------- ### Install phangorn from CRAN Source: https://klausvigo.github.io/phangorn/index.html Installs the latest stable release of the phangorn package from the CRAN repository. ```r install.packages("phangorn") ``` -------------------------------- ### Install phangorn Package Source: https://klausvigo.github.io/phangorn/articles/IntertwiningTreesAndNetworks.html Installs the phangorn package from CRAN and the latest development version from GitHub. Requires devtools for GitHub installation. ```R install.packages("phangorn", dependencies=TRUE) # install latest development version needs devtools install.packages("devtools", dependencies=TRUE) library(devtools) install_github("KlausVigo/phangorn") ``` -------------------------------- ### Install Biostrings Package Source: https://klausvigo.github.io/phangorn/index.html Installs the Biostrings package from Bioconductor, which may be a prerequisite for installing the development version of phangorn. ```r if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("Biostrings") ``` -------------------------------- ### Example: Terraces with Different Plotting Packages Source: https://klausvigo.github.io/phangorn/reference/terraces.html Shows how to use the terraces function with a pml object, specifying different plotting packages for visualization. ```R fit <- pml_bb(woodmouse, model="JC") terraces(fit, dist_fun="KF.dist") terraces(fit, pkg="scatterplot3d") terraces(fit, pkg="plot3D") terraces(fit, pkg="rgl") ``` -------------------------------- ### random.addition Source: https://klausvigo.github.io/phangorn/reference/parsimony.html Generates a starting tree using a random addition method, useful for parsimony searches. ```APIDOC ## random.addition ### Description Generates a starting tree using a random addition method, useful for parsimony searches. ### Usage ```R random.addition(data, tree = NULL, method = "fitch") ``` ### Arguments * `data`: A object of class phyDat containing sequences. * `tree`: A starting tree can be supplied. * `method`: One of 'fitch' or 'sankoff'. ``` -------------------------------- ### Example of gap_as_state with Laurasiatherian data Source: https://klausvigo.github.io/phangorn/reference/gap_as_state.html Demonstrates how to use gap_as_state on the Laurasiatherian dataset and inspect the resulting contrast matrix. This shows how gaps are incorporated as a new state. ```R data(Laurasiatherian) tmp <- gap_as_state(Laurasiatherian) contr <- attr(tmp, "contrast") rownames(contr) <- attr(tmp, "allLevels") contr ``` -------------------------------- ### Generate Initial Tree for Parsimony Source: https://klausvigo.github.io/phangorn/articles/Morphological.html Creates a starting tree for parsimony analysis using the random addition method. ```R mm_start <- random.addition(mm_pd) ``` -------------------------------- ### Install phangorn Development Version from r-universe Source: https://klausvigo.github.io/phangorn/index.html Installs the development version of the phangorn package from the r-universe repository. ```r install.packages('phangorn', repos = c('https://klausvigo.r-universe.dev', 'https://repo.r-wasm.org')) ``` -------------------------------- ### Constructing a phylogenetic tree using UPGMA Source: https://klausvigo.github.io/phangorn/reference/upgma.html This example demonstrates how to calculate a distance matrix from data and then use the upgma function to construct a phylogenetic tree. The resulting tree is then plotted. ```R data(Laurasiatherian) dm <- dist.ml(Laurasiatherian) tree <- upgma(dm) plot(tree) ``` -------------------------------- ### Stochastic Partitioning with pmlCluster Source: https://klausvigo.github.io/phangorn/reference/pmlCluster.html Demonstrates how to use pmlCluster to partition genes into clusters. Requires initial tree fitting and weight matrix calculation. The example is wrapped in \dontrun{} and requires setting a seed for reproducibility. ```R if (FALSE) { # \dontrun{ data(yeast) dm <- dist.logDet(yeast) tree <- NJ(dm) fit <- pml(tree,yeast) fit <- optim.pml(fit) weight <- xtabs(~ index+genes,attr(yeast, "index")) set.seed(1) sp <- pmlCluster(edge~rate, fit, weight, p=1:4) sp SH.test(sp) } # } ``` -------------------------------- ### Simulate Sequences from a PML Object Source: https://klausvigo.github.io/phangorn/reference/simSeq.html This example demonstrates how to simulate sequences using a fitted pml object. It first fits a GTR model with gamma distribution to existing data, then uses the fitted model to simulate new sequences. ```R if (FALSE) { # \dontrun{ data(Laurasiatherian) tree <- nj(dist.ml(Laurasiatherian)) fit <- pml(tree, Laurasiatherian, k=4) fit <- optim.pml(fit, optNni=TRUE, model="GTR", optGamma=TRUE) data <- simSeq(fit) } # } ``` -------------------------------- ### Bootstrap and Consensus Tree Generation Source: https://klausvigo.github.io/phangorn/reference/maxCladeCred.html This example demonstrates how to generate bootstrap trees using `bootstrap.phyDat` and then compute strict, majority rule, and maximum clade credibility consensus trees using `consensus` and `maxCladeCred` functions. It also shows how to obtain a majority rule consensus tree with compatible splits using `allCompat`. ```R data(Laurasiatherian) set.seed(42) bs <- bootstrap.phyDat(Laurasiatherian, FUN = function(x)upgma(dist.hamming(x)), bs=100) strict_consensus <- consensus(bs) majority_consensus <- consensus(bs, p=.5) all_compat <- allCompat(bs) max_clade_cred <- maxCladeCred(bs) ``` -------------------------------- ### Visualizing Age Estimates with Phylograms Source: https://klausvigo.github.io/phangorn/reference/densiTree.html Phylograms are useful for showing different age estimates. This example requires the 'PhyloOrchard' package and specific data. ```R require(PhyloOrchard) data(BinindaEmondsEtAl2007) BinindaEmondsEtAl2007 <- .compressTipLabel(BinindaEmondsEtAl2007) densiTree(BinindaEmondsEtAl2007, type="phylogram", col="red") ``` -------------------------------- ### Basic Tree Visualization Source: https://klausvigo.github.io/phangorn/reference/Ancestors.html Generates a random phylogenetic tree and displays it with node and tip labels. This is a setup step for demonstrating other tree utility functions. ```R tree <- rtree(10) plot(tree, show.tip.label = FALSE) nodelabels() tiplabels() ``` -------------------------------- ### ModelTest Example: Comparing Nucleotide Models Source: https://klausvigo.github.io/phangorn/reference/modelTest.html Demonstrates how to use modelTest to compare a selection of nucleotide substitution models (JC, K80, HKY, GTR) on a given dataset. Includes basic exploratory data analysis and extraction of the best model. ```R data(Laurasiatherian) T <- modelTest(Laurasiatherian, model = c("JC", "K80", "HKY", "GTR")) # Some exploratory data analysis plot(mT$TL, mT$logLik, xlim=c(3,6.5)) text(mT$TL, mT$logLik, labels=mT$Model, pos=4) fit_GTR_G <- as.pml(mT, "GTR+G(4)") fit_GTR_GW <- as.pml(mT, "GTR+GW(4)") fit_GTR_R <- as.pml(mT, "GTR+R(4)") plotRates(fit_GTR_G) plotRates(fit_GTR_GW, append=TRUE, col="red") plotRates(fit_GTR_R, append=TRUE, col="green") # extract best model (best_model <- as.pml(mT)) ``` -------------------------------- ### R: Identify splits in a network Source: https://klausvigo.github.io/phangorn/reference/identify.networx.html This example demonstrates how to use identify.networx to find splits in a network by clicking on a plotted network. Ensure the network is plotted before calling identify. ```R if (FALSE) { # \dontrun{ data(yeast) dm <- dist.ml(yeast) nnet <- neighborNet(dm) plot(nnet) identify(nnet) # click close to an edge } # } ``` -------------------------------- ### Update local clone from upstream Source: https://klausvigo.github.io/phangorn/CONTRIBUTING.html Before starting new work, ensure your local repository is up-to-date with the main branch of the original repository. ```bash git pull upstream main ``` -------------------------------- ### Load phangorn package Source: https://klausvigo.github.io/phangorn/articles/Networx.html Loads the phangorn package for phylogenetic analysis. Ensure the package is installed before running. ```R library(phangorn) ``` -------------------------------- ### ModelTest Example: Comparing Amino Acid Models Source: https://klausvigo.github.io/phangorn/reference/modelTest.html Shows how to use modelTest to compare amino acid substitution models (JTT, WAG, LG) and how to test all available models using parallel processing. ```R data(chloroplast) (mTAA <- modelTest(chloroplast, model=c("JTT", "WAG", "LG"))) # test all available amino acid models plan(multisession, workers = 2) (mTAA_all <- modelTest(chloroplast, model="all")) plan(sequential) ``` -------------------------------- ### Example: Assigning Edge Lengths with Bootstrap Samples Source: https://klausvigo.github.io/phangorn/reference/add_edge_length.html Demonstrates how to use `add_edge_length` with bootstrap samples to compute consensus tree edge lengths. Requires the ` Laurasiatherian` dataset and bootstrap resampling. ```R data("Laurasiatherian") set.seed(123) bs <- bootstrap.phyDat(Laurasiatherian, FUN=function(x)upgma(dist.ml(x)), bs=100) tree_compat <- allCompat(bs, rooted=TRUE) |> add_edge_length(bs) plot(tree_compat) add_boxplot(tree_compat, bs, boxwex=.7) ``` -------------------------------- ### Initialize PML Model Source: https://klausvigo.github.io/phangorn/reference/phangorn-internal.html Initializes the PML (Phylogenetic Maximum Likelihood) model with data and number of rate categories (k). This is a setup function for likelihood calculations. ```R pml.init(data, k = 1L) ``` -------------------------------- ### Plotting and Styling a Clade in a Phylogenetic Tree Source: https://klausvigo.github.io/phangorn/reference/cladePar.html This example demonstrates how to use cladePar to select and style a specific clade in a phylogenetic tree. First, a tree is generated and plotted with node labels. Then, cladePar is called to define the styling for a clade, and subsequently called again with the styling information to plot the tree with the modified clade. ```R tree <- rtree(10) plot(tree) nodelabels() x <- cladePar(tree, 12) cladePar(tree, 18, "blue", "blue", x=x, plot=TRUE) ``` -------------------------------- ### Initialize pmlPart with Formula and Data Source: https://klausvigo.github.io/phangorn/reference/pmlPart.html Demonstrates how to initialize a partitioned model fit using `pmlPart`. The formula specifies which parameters (e.g., edge, rate, inv) are optimized globally versus per partition. Requires an existing `pml` fit object and partition weights. ```R data(yeast) dm <- dist.logDet(yeast) tree <- NJ(dm) fit <- pml(tree,yeast) fits <- optim.pml(fit) weight=xtabs(~ index+genes,attr(yeast, "index"))[,1:10] sp <- pmlPart(edge ~ rate + inv, fits, weight=weight) sp ``` -------------------------------- ### Estimate Species Tree from Gene Trees Source: https://klausvigo.github.io/phangorn/reference/coalSpeciesTree.html This example demonstrates how to use coalSpeciesTree to estimate a species tree from a set of gene trees. Ensure the 'ape' package is installed and loaded for 'read.tree'. ```R tr1 <- read.tree(text = "(((B:0.05,C:0.05):0.01,D:0.06):0.04,A:0.1);") tr2 <- read.tree(text = "(((A:0.07,C:0.07):0.02,D:0.09):0.03,B:0.12);") TR <- c(tr1, tr2) sp_tree <- coalSpeciesTree(TR) ``` -------------------------------- ### Estimating Supertrees with Different Methods Source: https://klausvigo.github.io/phangorn/reference/superTree.html This example demonstrates how to use the superTree function with different methods (MRP, RF, SPR) on bootstrap samples of phylogenetic trees. It requires the Laurasiatherian dataset and bootstrap replicates generated by upgma. ```R data(Laurasiatherian) set.seed(1) bs <- bootstrap.phyDat(Laurasiatherian, FUN = function(x) upgma(dist.hamming(x)), bs=50) mrp_st <- superTree(bs, minit = 25, maxit=50) plot(mrp_st) # \donttest{ rf_st <- superTree(bs, method = "RF") spr_st <- superTree(bs, method = "SPR") # } ``` -------------------------------- ### Parsimony Ratchet Search Source: https://klausvigo.github.io/phangorn/reference/parsimony.html Performs a parsimony ratchet search for the best tree. This example uses reduced iterations for demonstration purposes; real analyses should use higher values for maxit, minit, and k. ```R # lower number of iterations for the example (to run less than 5 seconds), # keep default values (maxit, minit, k) or increase them for real life # analyses. treeRatchet <- pratchet(Laurasiatherian, start=tree, maxit=100, minit=5, k=5, trace=0) ``` -------------------------------- ### Set up Parallel Processing with future Source: https://klausvigo.github.io/phangorn/articles/Parallel.html Load necessary libraries, set the parallel processing plan using 'multisession' with a specified number of workers, and then execute a function like 'modelTest'. Finally, reset the plan to 'sequential' to revert to single-threaded execution. ```R library(phangorn) library(future) data("Laurasiatherian") plan(multisession, workers = 2) mt <- modelTest(Laurasiatherian, model = c("JC", "F81", "K80", "HKY", "SYM", "GTR")) plan(sequential) # run sequential again ``` -------------------------------- ### Explore Partitioned Model Fits Source: https://klausvigo.github.io/phangorn/reference/pmlPart.html Shows how to explore the results of a `pmlPart` fit, including log-likelihood, AIC, BIC, invariant site proportions, rates, base frequencies, and rate matrices for each partition. Also demonstrates alternative formula specifications and model comparison using AIC. ```R sp2 <- pmlPart(~ edge + inv, fits, weight=weight) sp2 AIC(sp2) ``` -------------------------------- ### dna2codon Source: https://klausvigo.github.io/phangorn/reference/dna2codon.html Translates DNA sequences to codon sequences. It can handle different genetic codes and starting positions for translation. ```APIDOC ## dna2codon ### Description Translates DNA sequences to codon sequences. ### Usage ```R dna2codon(x, codonstart = 1, code = 1, ambiguity = "---", ...) ``` ### Arguments * `x` (object): An object containing sequences. * `codonstart` (integer): An integer giving where to start the translation. This should be 1, 2, or 3, but larger values are accepted and have for effect to start the translation further within the sequence. * `code` (integer): The ncbi genetic code number for translation (see details). By default the standard genetic code is used. * `ambiguity` (character): Character for ambiguous character and no contrast is provided. * `...`: Further arguments passed to or from other methods. ### Value The function returns an object of class `phyDat`. ### Details Supports various genetic codes (1-26, excluding 7, 8, 17-20). Ambiguous characters and gaps are ignored. ### References https://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/index.cgi?chapter=cgencodes ### See also `trans`, `phyDat` ### Examples ```R data(Laurasiatherian) class(Laurasiatherian) #> [1] "phyDat" Laurasiatherian #> 47 sequences with 3179 character and 1605 different site patterns. #> The states are a c g t dna2codon(Laurasiatherian) #> 47 sequences with 1059 character and 914 different site patterns. #> The states are aaa aac aag aat aca acc acg act aga agc agg agt ata atc atg att caa cac cag cat cca ccc ccg cct cga cgc cgg cgt cta ctc ctg ctt gaa gac gag gat gca gcc gcg gct gga ggc ggg ggt gta gtc gtg gtt tac tat tca tcc tcg tct tgc tgg tgt tta ttc ttg ttt ``` ``` -------------------------------- ### Summarize Clan Data Source: https://klausvigo.github.io/phangorn/reference/getClans.html Use the `summary()` function to get an overview of clan data, including counts for different categories. ```r summary(divTab) ``` -------------------------------- ### allCompat Source: https://klausvigo.github.io/phangorn/reference/maxCladeCred.html Returns a 50% majority rule consensus tree with added compatible splits, similar to the `allcompat` option in MrBayes. This resulting tree does not have edge lengths. ```APIDOC ## Function: allCompat ### Description Returns a 50% majority rule consensus tree with added compatible splits, similar to the `allcompat` option in MrBayes. This tree has no edge length. ### Usage ```R allCompat(x, rooted = FALSE) ``` ### Arguments * `x` (multiPhylo or phylo): An object of class `multiPhylo` or `phylo`. * `rooted` (logical): If FALSE (default), the tree with highest maximum bipartition credibility is returned. ### Value A tree (an object of class `phylo`) with the highest clade credibility or a numeric vector of clade credibilities for each tree. ### Details `allCompat` returns a 50% majority rule consensus tree with added compatible splits similar to the option allcompat in MrBayes. This tree has no edge length. ### See also `consensus`, `consensusNet`, `prop.part`, `bootstrap.pml`, `plotBS`, `transferBootstrap`, `add_edge_length`, `add_boxplot` ### Author Klaus Schliep klaus.schliep@gmail.com ### Examples ```R data(Laurasiatherian) set.seed(42) bs <- bootstrap.phyDat(Laurasiatherian, FUN = function(x)upgma(dist.hamming(x)), bs=100) all_compat <- allCompat(bs) # Plotting example (requires graphics package) # old.par <- par(no.readonly = TRUE) # par(mfrow = c(2,2), mar = c(1,4,1,1)) # plot(all_compat, main="Majority consensus tree with compatible splits") # par(old.par) ``` ``` -------------------------------- ### Optimizing Parsimony Tree with SPR Source: https://klausvigo.github.io/phangorn/reference/parsimony.html Optimizes a parsimony tree using Subtree Pruning and Regrafting (SPR) rearrangements. This is an example of topology optimization. ```R treeSPR <- optim.parsimony(tree, Laurasiatherian) ``` -------------------------------- ### Free PML Model Source: https://klausvigo.github.io/phangorn/reference/phangorn-internal.html Resets the global state for PML (Phylogenetic Maximum Likelihood) calculations, freeing up resources. Call this before starting new analyses. ```R pml.free() ``` -------------------------------- ### Show Available Methods for pml Class Source: https://klausvigo.github.io/phangorn/reference/pml.html Displays all available methods for objects of class 'pml'. Use '?methods' for more details on accessing help and source code. ```R methods(class="pml") #> [1] AICc BIC anova glance logLik plot print simSeq #> [9] terraces update vcov #> see '?methods' for accessing help and source code ``` -------------------------------- ### bootstrap.phyDat Source: https://klausvigo.github.io/phangorn/reference/bootstrap.pml.html `bootstrap.phyDat` produces a list of bootstrapped data sets, which can then be used to estimate trees. ```APIDOC ## bootstrap.phyDat ### Description Produces a list of bootstrapped data sets. ### Usage ```R bootstrap.phyDat(x, FUN, bs = 100, multicore = FALSE, mc.cores = NULL, jumble = TRUE, ...) ``` ### Arguments * `x` (phyDat): An object of class `phyDat`. * `FUN` (function): The function to estimate the trees. * `bs` (numeric): Number of bootstrap samples. Default is 100. * `multicore` (logical): Whether models should be estimated in parallel. Default is FALSE. * `mc.cores` (numeric): The number of cores to use during bootstrap. Only supported on UNIX-alike systems. * `jumble` (logical): Logical, jumble the order of the sequences. Default is TRUE. * `...`: Further parameters used by `optim.pml` or `plot.phylo`. ### Value Returns a list of bootstrapped data sets. ``` -------------------------------- ### Plotting a Tip-Dated Phylogeny Source: https://klausvigo.github.io/phangorn/articles/Trees.html Plots a tip-dated phylogenetic tree with aligned tip labels and a time scale. Ensure the 'phangorn' and 'ape' packages are installed and loaded. ```R plot(fit_td, align.tip.label=TRUE) ``` -------------------------------- ### Read Sequence Data and Tree Source: https://klausvigo.github.io/phangorn/articles/AdvancedFeatures.html Reads sequence data and a phylogenetic tree from specified files. Ensure the 'phangorn' package is installed and the file paths are correct. ```R fdir <- system.file("extdata/trees", package = "phangorn") hiv_2_nef <- read.phyDat(file.path(fdir, "seqfile.txt"), format="sequential") tree <- read.tree(file.path(fdir, "tree.txt")) ``` -------------------------------- ### add.tips Source: https://klausvigo.github.io/phangorn/reference/add.tips.html Binds new tips to nodes or existing tips of a phylogenetic tree. ```APIDOC ## add.tips ### Description Binds new tips to nodes or existing tips of a phylogenetic tree. ### Usage ``` add.tips(tree, tips, where, edge.length = NULL) ``` ### Arguments * **tree** (phylo) - An object of class "phylo". * **tips** (character vector) - A character vector containing the names of the tips to add. * **where** (integer or character vector) - A vector of the same length as `tips` specifying the node or tip number where each new tip should be added. * **edge.length** (numeric vector, optional) - An optional numeric vector for edge lengths. ### Value An object of class phylo. ### Examples ```R tree <- rcoal(10) plot(tree) nodelabels() tiplabels() tree1 <- add.tips(tree, c("A", "B", "C"), c(1,2,15)) plot(tree1) ``` ``` -------------------------------- ### Calculate and Visualize Distance Hadamard Spectra Source: https://klausvigo.github.io/phangorn/reference/distanceHadamard.html This example demonstrates how to use distanceHadamard with a Hamming distance matrix derived from yeast data. It then visualizes the resulting network. ```R data(yeast) dm <- dist.hamming(yeast) dm <- as.matrix(dm) fit <- distanceHadamard(dm) lento(fit) plot(as.networx(fit)) ``` -------------------------------- ### Write Network with Bootstrap Support to Nexus Source: https://klausvigo.github.io/phangorn/articles/IntertwiningTreesAndNetworks.html Exports a network object, including bootstrap support information, to a Nexus file for visualization in SplitsTree. ```R # write.nexus.networx(y,"NN.with.bs.support.nxs") ``` -------------------------------- ### Get Clans from a Phylogenetic Tree Source: https://klausvigo.github.io/phangorn/reference/getClans.html Demonstrates how to use the getClans function to identify clades within a phylogenetic tree. Requires the tree object to be generated first. ```r set.seed(111) tree <- rtree(10) getClans(tree) ``` -------------------------------- ### baseFreq() glance() composition_test() summary() print() Source: https://klausvigo.github.io/phangorn/reference/index.html Provides summary statistics and composition tests for sequence alignments. ```APIDOC ## baseFreq() glance(__) composition_test() summary(__) print(__) ### Description Summaries of alignments and base frequencies. ### Parameters None explicitly documented. ``` -------------------------------- ### Load and Inspect Laurasiatherian Data in R Source: https://klausvigo.github.io/phangorn/reference/Laurasiatherian.html This snippet demonstrates how to load the Laurasiatherian dataset and inspect its structure using R. Ensure the 'phangorn' package is installed and loaded. ```r data(Laurasiatherian) str(Laurasiatherian) ``` -------------------------------- ### add.tips() Source: https://klausvigo.github.io/phangorn/reference/index.html Adds new tips (taxa) to an existing phylogenetic tree. ```APIDOC ## add.tips() ### Description Add tips to a tree. ### Parameters None explicitly documented. ``` -------------------------------- ### Compute all trees topologies Source: https://klausvigo.github.io/phangorn/reference/allTrees.html Computes all bifurcating tree topologies for rooted or unrooted trees with up to 10 tips. The number of trees grows rapidly with the number of tips. ```APIDOC ## Function: allTrees ### Description Computes all bifurcating tree topologies for rooted or unrooted trees with up to 10 tips. The number of trees grows fast. ### Usage ```R allTrees(n, rooted = FALSE, tip.label = NULL) ``` ### Arguments * **n** (numeric) - Number of tips (<=10). * **rooted** (logical) - Rooted or unrooted trees (default: FALSE). * **tip.label** (character vector) - Tip labels. ### Value An object of class `multiPhylo`. ### See also `rtree`, `nni`, `howmanytrees`, `dfactorial` ### Examples ```R trees <- allTrees(5) old.par <- par(no.readonly = TRUE) par(mfrow = c(3,5)) for(i in 1:15)plot(trees[[i]]) par(old.par) ``` ``` -------------------------------- ### Assign edge length using parsimony_edgelength Source: https://klausvigo.github.io/phangorn/reference/acctran.html Assigns edge lengths to a tree, representing the number of substitutions. This example demonstrates its use after an initial tree construction with `pratchet`. ```R data(Laurasiatherian) # lower number of iterations for the example, to run time less than 5 sec. treeRatchet <- pratchet(Laurasiatherian, minit=5, k=5, trace=0) # assign edge length (number of substitutions) treeRatchet <- parsimony_edgelength(treeRatchet, Laurasiatherian) plot(midpoint(treeRatchet)) add.scale.bar(0,0, length=100) ``` -------------------------------- ### bootstrap.pml() bootstrap.phyDat() Source: https://klausvigo.github.io/phangorn/reference/index.html Performs bootstrapping on phylogenetic trees or data. ```APIDOC ## bootstrap.pml() bootstrap.phyDat() ### Description Bootstrap analysis for phylogenetic trees and data. ### Parameters None explicitly documented. ``` -------------------------------- ### codonTest Function Source: https://klausvigo.github.io/phangorn/reference/codonTest.html This function tests for positive selection by comparing different codon substitution models. It can optimize codon frequencies and handle different translation start points. ```APIDOC ## codonTest ### Description Tests for positive selection similar to programs like PAML or HyPhy. Allows for different options in deriving codon frequencies and implementing models like M0, M1a, and M2a. ### Usage ```R codonTest(tree, object, model = c("M0", "M1a", "M2a"), frequencies = "F3x4", opt_freq = FALSE, codonstart = 1, control = pml.control(maxit = 20), ...) ``` ### Arguments * **tree** (phylogenetic tree): A phylogenetic tree object. * **object** (phyDat): An object of class phyDat. * **model** (vector of strings): A vector containing the substitution models to compare with each other or "all" to test all available models. Defaults to c("M0", "M1a", "M2a"). * **frequencies** (string or vector): Defines how to compute the codon frequencies. Options include "equal", "F1x4", "F3x4", or "empirical". Defaults to "F3x4". * **opt_freq** (boolean): Optimize frequencies. Currently ignored. * **codonstart** (integer): An integer giving where to start the translation. Defaults to 1. * **control** (list): A list of parameters for controlling the fitting process. Defaults to pml.control(maxit = 20). * **...**: Further arguments passed to or from other methods. ### Value A list containing: * **summary** (data.frame): Contains the log-likelihood, number of estimated parameters, etc., of all tested models. * **posterior** (object): Contains the posterior probability for the rate class for each site and the estimates of the defined models. ### Details `codonTest` allows to test for positive selection similar to programs like PAML (Yang ) or HyPhy (Kosakovsky Pond et al. 2005). There are several options for deriving the codon frequencies: "equal" (1/61), "F1x4" and "F3x4" (derived from nucleotide frequencies), or "empirical" codon frequencies. The frequencies can be estimated via maximum likelihood. So far the M0 model (Goldman and Yang 2002), M1a and M2a are implemented. The M0 model is always computed, the others are optional. Convergence may be very slow and sometimes fails. ### References * Ziheng Yang (2014). _Molecular Evolution: A Statistical Approach_. Oxford University Press, Oxford * Sergei L. Kosakovsky Pond, Simon D. W. Frost, Spencer V. Muse (2005) HyPhy: hypothesis testing using phylogenies, _Bioinformatics_ , **21(5)** : 676–679, doi:10.1093/bioinformatics/bti079 * Nielsen, R., and Z. Yang. (1998) Likelihood models for detecting positively selected amino acid sites and applications to the HIV-1 envelope gene. _Genetics_ , **148** : 929–936 ### See also `pml`, `pmlMix`, `modelTest`, `AIC` ### Author Klaus Schliep klaus.schliep@gmail.com ### Examples ```R # load woodmouse data from ape data(woodmouse) dat_codon <- dna2codon(as.phyDat(woodmouse), code=2) tree <- NJ(dist.ml(dat_codon)) # optimize the model the old way fit <- pml(tree, dat_codon, bf="F3x4") M0 <- optim.pml(fit, model="codon1") # Now using the codonTest function fit_codon <- codonTest(tree, dat_codon) fit_codon plot(fit_codon, "M1a") ``` ``` -------------------------------- ### Generate All Possible Bifurcating Tree Topologies Source: https://klausvigo.github.io/phangorn/articles/MLbyHand.html Use allTrees to compute all possible bifurcating tree topologies for a given number of tips. Useful for simulation studies. Note the exponential growth in tree count. ```r trees <- allTrees(5) par(mfrow=c(3,5), mar=rep(0,4)) for(i in 1:15)plot(trees[[i]], cex=1, type="u") ``` -------------------------------- ### Get Clips from a Phylogenetic Tree Source: https://klausvigo.github.io/phangorn/reference/getClans.html Illustrates the usage of the getClips function, which extracts specific clades or 'clips' from a phylogenetic tree. The 'all=TRUE' argument retrieves all possible clips. ```r getClips(tree, all=TRUE) ``` -------------------------------- ### Translate DNA to Codons Source: https://klausvigo.github.io/phangorn/reference/dna2codon.html Translates DNA sequences to codon sequences using the dna2codon function. Supports specifying the starting position, genetic code, and handling of ambiguous characters. ```R data(Laurasiatherian) class(Laurasiatherian) #> [1] "phyDat" Laurasiatherian #> 47 sequences with 3179 character and 1605 different site patterns. #> The states are a c g t dna2codon(Laurasiatherian) #> 47 sequences with 1059 character and 914 different site patterns. #> The states are aaa aac aag aat aca acc acg act aga agc agg agt ata atc atg att caa cac cag cat cca ccc ccg cct cga cgc cgg cgt cta ctc ctg ctt gaa gac gag gat gca gcc gcg gct gga ggc ggg ggt gta gtc gtg gtt tac tat tca tcc tcg tct tgc tgg tgt tta ttc ttg ttt ``` -------------------------------- ### Compute all tree topologies Source: https://klausvigo.github.io/phangorn/reference/allTrees.html Generates all bifurcating tree topologies for a specified number of tips. Supports rooted or unrooted trees and custom tip labels. The number of trees grows rapidly with the number of tips (n <= 10). ```R trees <- allTrees(5) old.par <- par(no.readonly = TRUE) par(mfrow = c(3,5)) for(i in 1:15)plot(trees[[i]]) par(old.par) ``` -------------------------------- ### Plot 3D Consensus Network Source: https://klausvigo.github.io/phangorn/reference/consensusNet.html Plots a consensus network in 3D using the rgl package. This provides an interactive visualization of the network. Ensure rgl is installed and open3d() is called before plotting. ```R library(rgl) open3d() plot(cnet, type = "3D", show.tip.label=FALSE, show.nodes=TRUE) ``` -------------------------------- ### Fit Mixture Model using Real Data Example Source: https://klausvigo.github.io/phangorn/reference/pmlMix.html Applies the pmlMix function to a real biological dataset (Laurasiatherian mammals) to fit a mixture model with edge and rate optimization. ```R data(Laurasiatherian) dm <- dist.logDet(Laurasiatherian) tree <- NJ(dm) fit <- pml(tree, Laurasiatherian) fit <- optim.pml(fit) fit2 <- update(fit, k=4, site.rate="free_rate") fit2 <- optim.pml(fit2, optGamma=TRUE) fitMix <- pmlMix(edge ~ rate, fit, m=4) fitMix ``` -------------------------------- ### Check package with devtools Source: https://klausvigo.github.io/phangorn/CONTRIBUTING.html After making changes, use `devtools::check()` to verify the package. Aim for zero errors and warnings. ```r devtools::check() ```