/
treeSampler.R
36 lines (36 loc) · 1.17 KB
/
treeSampler.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#' Subset trees from posterior distribution of trees.
#'
#' This function randomly samples a subset of trees from a posterior
#' distribution of trees derived from multiple runs of MrBayes.
#'
#' @param wd A path to the working directory with the distributions of
#' multiple phylogenetic trees.
#' @param n The desired number of subsets of trees. This defaults to 100.
#' @param pattern An optional regular expression specifying the file extension.
#' @param \dots arguments passed among methods.
#'
#' @rdname tree_sampler
#' @importFrom ape read.tree
#' @export
#'
#' @return An object of class "multiPhylo" with the subset of trees.
#'
#' @author Dominic Bennett & Harith Farooq \email{harithmorgadinho@gmail.com}
#'
#'
#' @export
tree_sampler <- function(wd, n = 100, pattern = ".tre", ...) {
read_treelines <- function(fl) {
readLines(con = fl)
}
sampler <- function(i) {
read.tree(text = sample(tree_lines, 1))
}
fls <- list.files(path = wd, pattern = pattern)
fls <- file.path(wd, fls)
tree_lines <- lapply(X = fls, FUN = read_treelines)
tree_lines <- unlist(tree_lines)
trees <- lapply(X = seq_len(n), FUN = sampler)
class(trees) <- 'multiPhylo'
trees
}