Skip to content

Instantly share code, notes, and snippets.

@cromanpa94
Created July 27, 2021 16:45
Show Gist options
  • Save cromanpa94/d627fc1754ffd794b991d383333c8a51 to your computer and use it in GitHub Desktop.
Save cromanpa94/d627fc1754ffd794b991d383333c8a51 to your computer and use it in GitHub Desktop.
TreeToConstraints.R
#Fasttree tree constraint in R
#http://www.microbesonline.org/fasttree/constrained.html
#Packages
library(ape)
library(phylobase)
library(adephylo)
library(bio3d)
library(pbapply)
#Use either this function of the original (listTips). listTips2 adds a progress bar.
listTips2 <- function(x){
## if(!require(phylobase)) stop("phylobase package is not installed")
## conversion from phylo, phylo4 and phylo4d
x <- as(x, "phylo4")
## check phylo4 object
if (is.character(checkval <- checkPhylo4(x))) stop(checkval)
## computations
nodIdx <- nTips(x)+1
nodIdx <- nodIdx:(nodIdx+nNodes(x)-1)
res <- pblapply(nodIdx, function(i) descendants(x, i))
if(hasNodeLabels(x)) {names(res) <- nodeLabels(x)}
return(res)
}
#The target tree
x2<-rtree(20) #Simulated tree
#x2<-read.tree('yourTree.tre') #Tree file
#List the tips per node and create a matrix (rows tips, columns nodes)
listNodes<-listTips2(x2)
dat<-as.data.frame(sapply(listNodes, function(x){
ifelse(x2$tip.label %in% names(x), 1,0)
}))
row.names(dat)<-x2$tip.label
dat<-as.matrix(dat)
#Create a fasta from the matrix
datF<-as.fasta(dat)
#Export fasta file
write.fasta(datF, file = 'cst.ft')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment